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): let people pin their key numbers on the home (#120526)

Shy Alterfb6570ea83e5
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index 040b5e813bf2..30b6f5111042 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -142,6 +142,7 @@ rules:
|CustomPropertyValue
|DAG
|TodayHighlights
+ |TodayPulsePins
|Dashboard
|DashboardTemplate
|DashboardWidget
@@ -615,6 +616,7 @@ rules:
|CustomPropertyValue
|DAG
|TodayHighlights
+ |TodayPulsePins
|Dashboard
|DashboardTemplate
|DashboardWidget
diff --git a/frontend/src/scenes/project-homepage/today/Today.scss b/frontend/src/scenes/project-homepage/today/Today.scss
index b86a5b0db787..43b28abb4770 100644
--- a/frontend/src/scenes/project-homepage/today/Today.scss
+++ b/frontend/src/scenes/project-homepage/today/Today.scss
@@ -207,6 +207,31 @@ html[data-today-transition]::view-transition-new(root) {
}
}
+.TodayPulse__edit {
+ opacity: 0;
+ transition: opacity 150ms var(--today-ease);
+
+ &.TodayPulse__edit--shown,
+ .TodayHome:has(.TodayHome__intro:hover, .TodayPulse:hover) &,
+ &:focus-visible,
+ &[data-popup-open] {
+ opacity: 1;
+ }
+
+ @media (hover: none) {
+ opacity: 1;
+ }
+}
+
+.TodayPulse__unavailable {
+ overflow: hidden;
+ font-size: 13px;
+ line-height: calc(19px * 1.2);
+ color: var(--today-muted);
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
.TodayPulse__metric {
display: flex;
flex-direction: column;
@@ -665,6 +690,14 @@ html[data-today-transition]::view-transition-new(root) {
color: var(--today-muted);
}
+.TodayHome__metaRow {
+ display: flex;
+ gap: 8px;
+ align-items: center;
+ justify-content: space-between;
+ min-width: 0;
+}
+
.TodayHome__intro {
margin-top: 8px;
color: var(--today-faint);
diff --git a/frontend/src/scenes/project-homepage/today/Today.stories.tsx b/frontend/src/scenes/project-homepage/today/Today.stories.tsx
index dfaa0e88e014..191aa1720364 100644
--- a/frontend/src/scenes/project-homepage/today/Today.stories.tsx
+++ b/frontend/src/scenes/project-homepage/today/Today.stories.tsx
@@ -567,6 +567,7 @@ const HIGHLIGHTS: HighlightsApi = {
generated_at: '2026-09-28T18:00:00Z',
day: '2026-09-28',
refresh_at: '2026-09-29T00:00:00Z',
+ pins: [],
pulse: [
{
key: 'insight:wKu1pSx2',
@@ -581,6 +582,7 @@ const HIGHLIGHTS: HighlightsApi = {
period_starts: PERIOD_STARTS(12, 'week'),
reason: 'dashboard',
dashboard_name: 'Growth',
+ dashboard_id: 41,
opened_days: 9,
last_opened: '2026-09-27',
previous_value: 3956,
@@ -603,6 +605,7 @@ const HIGHLIGHTS: HighlightsApi = {
period_starts: PERIOD_STARTS(28, 'day'),
reason: 'key_metric',
dashboard_name: null,
+ dashboard_id: null,
opened_days: null,
last_opened: null,
previous_value: 1017,
@@ -621,6 +624,7 @@ const HIGHLIGHTS: HighlightsApi = {
period_starts: PERIOD_STARTS(28, 'day'),
reason: 'key_metric',
dashboard_name: null,
+ dashboard_id: null,
opened_days: null,
last_opened: null,
previous_value: 353,
@@ -639,6 +643,7 @@ const HIGHLIGHTS: HighlightsApi = {
period_starts: PERIOD_STARTS(28, 'day'),
reason: 'key_metric',
dashboard_name: null,
+ dashboard_id: null,
opened_days: null,
last_opened: null,
previous_value: 18012,
@@ -715,6 +720,88 @@ const HIGHLIGHTS: HighlightsApi = {
],
}
+const SAVED_INSIGHTS = [
+ { id: 1, short_id: 'chk01', name: 'Checkout conversion' },
+ { id: 2, short_id: 'rev01', name: 'Refunds' },
+ { id: 3, short_id: 'arr01', name: 'Monthly recurring revenue' },
+ { id: 4, short_id: 'ret01', name: 'Week 1 retention' },
+ { id: 5, short_id: 'trl01', name: 'Trial to paid' },
+]
+
+const CHECKOUT_METRIC: HighlightsApi['pulse'][number] = {
+ ...HIGHLIGHTS.pulse[0],
+ key: 'insight:chk01',
+ name: 'Checkout conversion',
+ value: 0.342,
+ change_pct: 4.1,
+ series: [0.31, 0.32, 0.3, 0.33, 0.32, 0.31, 0.33, 0.32, 0.33, 0.33, 0.329, 0.342],
+ url: '/insights/chk01',
+ value_format: { format: 'percentage_scaled', prefix: null, postfix: null, decimal_places: 1 },
+ reason: 'routine',
+ dashboard_name: null,
+ dashboard_id: null,
+ previous_value: 0.329,
+ movers: [],
+}
+
+let storyPins: { key: string; name: string }[] = []
+let storyComputingCalls = 0
+
+const RETENTION_METRIC: HighlightsApi['pulse'][number] = {
+ ...CHECKOUT_METRIC,
+ key: 'insight:ret01',
+ name: 'Week 1 retention',
+ value: 0.412,
+ change_pct: -1.2,
+ series: [0.42, 0.41, 0.43, 0.42, 0.4, 0.41, 0.42, 0.41, 0.42, 0.42, 0.417, 0.412],
+ url: '/insights/ret01',
+ previous_value: 0.417,
+}
+
+const REVENUE_METRIC: HighlightsApi['pulse'][number] = {
+ ...CHECKOUT_METRIC,
+ key: 'insight:arr01',
+ name: 'Monthly recurring revenue',
+ value: 48200,
+ change_pct: 3.4,
+ series: [39000, 40100, 41000, 41800, 42600, 43300, 44000, 44900, 45700, 46200, 46600, 48200],
+ url: '/insights/arr01',
+ value_format: { format: 'numeric', prefix: '$', postfix: null, decimal_places: 0 },
+ previous_value: 46600,
+}
+
+let storyLastReady: HighlightsApi | null = null
+
+function storyHighlights(): HighlightsApi {
+ if (storyComputingCalls > 0) {
+ storyComputingCalls -= 1
+ return storyLastReady
+ ? { ...storyLastReady, status: 'computing' }
+ : { ...HIGHLIGHTS, status: 'computing', generated_at: null, pulse: [], items: [] }
+ }
+ const offered = [CHECKOUT_METRIC, RETENTION_METRIC, REVENUE_METRIC, ...HIGHLIGHTS.pulse]
+ const chosen = storyPins.flatMap((pin) => {
+ const metric = offered.find((candidate) => candidate.key === pin.key)
+ return metric ? [metric] : []
+ })
+ const suggested = HIGHLIGHTS.pulse.filter((metric) => !storyPins.some((pin) => pin.key === metric.key))
+ const pins = storyPins.map((pin) => ({
+ key: pin.key,
+ status: chosen.some((metric) => metric.key === pin.key) ? ('ready' as const) : ('unavailable' as const),
+ }))
+ storyLastReady = { ...HIGHLIGHTS, pulse: [...chosen, ...suggested].slice(0, 4), pins }
+ return storyLastReady
+}
+
+function keepNumbers(pins: { key: string; name: string }[]) {
+ return function KeepNumbers(Story: () => JSX.Element): JSX.Element {
+ storyPins = pins
+ storyComputingCalls = 0
+ storyLastReady = null
+ return <Story />
+ }
+}
+
const meta: Meta = {
component: App,
title: 'Scenes-App/Project Homepage/Today',
@@ -758,7 +845,13 @@ const meta: Meta = {
],
'/api/users/@me/integrations/': { results: [] },
'/api/users/@me/integrations/slack/linkable_workspaces/': { results: [] },
- '/api/projects/:team_id/today/highlights/': HIGHLIGHTS,
+ '/api/projects/:team_id/today/highlights/': () => [200, storyHighlights()],
+ '/api/projects/:team_id/today/pulse_pins/': () => [200, { pins: storyPins }],
+ '/api/projects/:team_id/insights/': ({ request }) => {
+ const search = (new URL(request.url).searchParams.get('search') ?? '').toLowerCase()
+ const results = SAVED_INSIGHTS.filter((insight) => insight.name.toLowerCase().includes(search))
+ return [200, { results, count: results.length, next: null, previous: null }]
+ },
'/api/projects/:team_id/task_channels/': SPACES,
'/api/projects/:team_id/task_channels/:id/': (req) => [
200,
@@ -853,6 +946,14 @@ const meta: Meta = {
],
},
},
+ put: {
+ '/api/projects/:team_id/today/pulse_pins/': async ({ request }) => {
+ const body = (await request.json()) as { pins: { key: string; name: string }[] }
+ storyPins = body.pins
+ storyComputingCalls = 1
+ return [200, { pins: storyPins }]
+ },
+ },
}),
],
parameters: {
@@ -868,7 +969,16 @@ export default meta
type Story = StoryObj<{}>
-export const Home: Story = {}
+export const Home: Story = { decorators: [keepNumbers([])] }
+
+export const HomeWithKeptNumbers: Story = {
+ decorators: [
+ keepNumbers([
+ { key: 'insight:chk01', name: 'Checkout conversion' },
+ { key: 'activity_event', name: 'Active users' },
+ ]),
+ ],
+}
export const HomeWithSampleReports: Story = {
parameters: { pageUrl: `${urls.projectHomepage()}?sample=1` },
diff --git a/frontend/src/scenes/project-homepage/today/TodayHomePage.tsx b/frontend/src/scenes/project-homepage/today/TodayHomePage.tsx
index 2b01d455c5cb..215a4c709ab0 100644
--- a/frontend/src/scenes/project-homepage/today/TodayHomePage.tsx
+++ b/frontend/src/scenes/project-homepage/today/TodayHomePage.tsx
@@ -9,6 +9,7 @@ import { TodayForYou } from './TodayForYou'
import { todayHighlightsLogic } from './todayHighlightsLogic'
import { reportIdFromPath, todayLogic } from './todayLogic'
import { TodayPulse } from './TodayPulse'
+import { TodayPulseEditor } from './TodayPulseEditor'
import { TodayRecents } from './TodayRecents'
import { TodaySampleBanner } from './TodaySampleBanner'
@@ -48,7 +49,7 @@ function TodayMetaLine(): JSX.Element {
export function TodayHomePage(): JSX.Element {
const { greeting, isNewProject, recentObjects, returnFocusReportId } = useValues(todayLogic)
const { setReturnFocusReportId } = useActions(todayLogic)
- const { highlights, highlightsPending } = useValues(todayHighlightsLogic)
+ const { highlights, highlightsPending, pulseTiles, pulsePinsLoaded } = useValues(todayHighlightsLogic)
const rootRef = useRef<HTMLDivElement>(null)
useLayoutEffect(() => {
@@ -84,13 +85,16 @@ export function TodayHomePage(): JSX.Element {
{greeting}
</Text>
</div>
- <TodayMetaLine />
+ <div className="TodayHome__metaRow">
+ <TodayMetaLine />
+ {!highlightsPending && highlights && pulsePinsLoaded ? <TodayPulseEditor /> : null}
+ </div>
</section>
<div className="TodayHome__body">
{highlightsPending ? (
<TodayPulseSkeleton />
- ) : highlights && highlights.pulse.length > 0 ? (
- <TodayPulse metrics={highlights.pulse} />
+ ) : highlights && pulseTiles.length > 0 ? (
+ <TodayPulse metrics={pulseTiles} />
) : null}
{isNewProject && recentObjects.length === 0 ? <TodayExplore /> : <TodayRecents />}
<TodayForYou />
diff --git a/frontend/src/scenes/project-homepage/today/TodayPulse.tsx b/frontend/src/scenes/project-homepage/today/TodayPulse.tsx
index 18298298e522..c2d0addef5ee 100644
--- a/frontend/src/scenes/project-homepage/today/TodayPulse.tsx
+++ b/frontend/src/scenes/project-homepage/today/TodayPulse.tsx
@@ -1,17 +1,28 @@
import { useActions, useValues } from 'kea'
+import { type RefObject, useLayoutEffect, useRef } from 'react'
+
+import { Skeleton } from '@posthog/quill'
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 { urls } from 'scenes/urls'
import type { CurrencyCode, TrendsFilter } from '~/queries/schema/schema-general'
+import type { InsightShortId } from '~/types'
import type { HighlightMetricApi } from 'products/today/frontend/generated/api.schemas'
import { TodayChange } from './TodayChange'
-import { todayHighlightsLogic } from './todayHighlightsLogic'
+import {
+ type PulsePlaceholderTile,
+ type TodayPulseTile,
+ isPlaceholderTile,
+ pulsePinLimitReason,
+ todayHighlightsLogic,
+} from './todayHighlightsLogic'
import { todayNumber } from './todayNumbers'
import { TodayPulseCard } from './TodayPulseCard'
import { TodayPulseHoverCard } from './TodayPulseHoverCard'
@@ -56,13 +67,94 @@ function metricFormatter(metric: HighlightMetricApi, currency: CurrencyCode): (v
return (value) => formatAggregationAxisValue(trendsFilter, value, currency)
}
-export function TodayPulse({ metrics }: { metrics: HighlightMetricApi[] }): JSX.Element {
+function TodayPulsePlaceholder({ tile }: { tile: PulsePlaceholderTile }): JSX.Element {
+ if (tile.placeholder === 'computing') {
+ return (
+ <>
+ <span className="TodayPulse__name">{tile.name}</span>
+ <span className="TodayPulse__row">
+ <span className="TodayPulse__value">
+ <Skeleton className="inline-block h-4 w-20 align-middle" />
+ </span>
+ </span>
+ <span className="TodayPulse__spark">
+ <Skeleton className="h-3 w-full" />
+ </span>
+ </>
+ )
+ }
+ const shortId = tile.key.startsWith('insight:') ? tile.key.slice('insight:'.length) : null
+ const content = (
+ <>
+ <span className="TodayPulse__name">{tile.name}</span>
+ <span className="TodayPulse__row">
+ <span className="TodayPulse__unavailable">
+ {shortId ? "Can't show this insight" : "Can't show this number"}
+ </span>
+ </span>
+ </>
+ )
+ return shortId ? (
+ <LinkPrimitive to={urls.insightView(shortId as InsightShortId)} className="TodayPulse__link">
+ {content}
+ </LinkPrimitive>
+ ) : (
+ content
+ )
+}
+
+const REORDER_MS = 220
+
+function useSettleOnReorder(listRef: RefObject<HTMLUListElement>, order: string): void {
+ const previous = useRef(order)
+ useLayoutEffect(() => {
+ const before = previous.current.split('|')
+ previous.current = order
+ if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
+ return
+ }
+ listRef.current?.querySelectorAll<HTMLElement>('[data-pulse-key]').forEach((tile, index) => {
+ const was = before.indexOf(tile.dataset.pulseKey ?? '')
+ if (was !== -1 && was !== index) {
+ tile.animate(
+ [
+ { opacity: 0, transform: 'translateY(4px)' },
+ { opacity: 1, transform: 'none' },
+ ],
+ {
+ duration: REORDER_MS,
+ easing: 'cubic-bezier(0.2, 0, 0, 1)',
+ }
+ )
+ }
+ })
+ }, [order, listRef])
+}
+
+export function TodayPulse({ metrics }: { metrics: TodayPulseTile[] }): JSX.Element {
+ const listRef = useRef<HTMLUListElement>(null)
+ useSettleOnReorder(listRef, metrics.map((tile) => tile.key).join('|'))
const { baseCurrency } = useValues(teamLogic)
- const { pulseMetricOpened, pulseMetricPreviewed } = useActions(todayHighlightsLogic)
+ const { pulsePins, pulsePinsUnavailableReason } = useValues(todayHighlightsLogic)
+ const { pulseMetricOpened, pulseMetricPreviewed, togglePulsePin, holdPulseOrder, releasePulseOrder } =
+ useActions(todayHighlightsLogic)
return (
- <ul className="TodayPulse" aria-label="Key numbers, against the period before">
+ <ul ref={listRef} className="TodayPulse" aria-label="Key numbers, against the period before">
{metrics.map((metric, position) => {
+ if (isPlaceholderTile(metric)) {
+ return (
+ <li
+ key={metric.key}
+ data-pulse-key={metric.key}
+ className="TodayPulse__metric"
+ aria-busy={metric.placeholder === 'computing'}
+ >
+ <TodayPulsePlaceholder tile={metric} />
+ </li>
+ )
+ }
const isInsight = metric.key.startsWith('insight:')
+ const pinned = pulsePins.some((pin) => pin.key === metric.key)
const tone = isInsight ? 'neutral' : metricTone(metric.change_pct, metric.value)
const formatValue = metric.value_format ? metricFormatter(metric, baseCurrency) : todayNumber
const content = (
@@ -85,15 +177,35 @@ export function TodayPulse({ metrics }: { metrics: HighlightMetricApi[] }): JSX.
</>
)
return (
- <li key={metric.key} className="TodayPulse__metric">
+ <li key={metric.key} data-pulse-key={metric.key} className="TodayPulse__metric">
<TodayPulseHoverCard
- onOpen={() => pulseMetricPreviewed(metric, position)}
+ onOpenChange={(open) => {
+ if (open) {
+ pulseMetricPreviewed(metric, position)
+ holdPulseOrder(
+ metric.key,
+ metrics.map((tile) => tile.key)
+ )
+ } else {
+ releasePulseOrder(metric.key)
+ }
+ }}
card={
<TodayPulseCard
metric={metric}
tone={tone}
formatValue={metric.value_format ? formatValue : humanFriendlyNumber}
onOpen={() => pulseMetricOpened(metric, position)}
+ pinned={pinned}
+ pinDisabledReason={
+ pulsePinsUnavailableReason ?? pulsePinLimitReason(pulsePins.length, pinned)
+ }
+ onTogglePin={() =>
+ togglePulsePin(
+ { key: metric.key, name: metric.name, dashboard_id: metric.dashboard_id },
+ 'hover_card'
+ )
+ }
/>
}
>
diff --git a/frontend/src/scenes/project-homepage/today/TodayPulseCard.tsx b/frontend/src/scenes/project-homepage/today/TodayPulseCard.tsx
index c37c0f732bf6..66da93706d98 100644
--- a/frontend/src/scenes/project-homepage/today/TodayPulseCard.tsx
+++ b/frontend/src/scenes/project-homepage/today/TodayPulseCard.tsx
@@ -1,6 +1,6 @@
import { useState } from 'react'
-import { IconArrowRight, IconInfo } from '@posthog/icons'
+import { IconArrowRight, IconInfo, IconPin, IconPinFilled } from '@posthog/icons'
import {
Button,
Collapsible,
@@ -33,7 +33,7 @@ const PERIOD_FORMATS: Record<HighlightMetricApi['interval'], string> = {
}
function openLabel(metric: HighlightMetricApi): string {
- if (metric.reason === 'dashboard') {
+ if (metric.dashboard_id !== null || metric.reason === 'dashboard') {
return metric.dashboard_name ? `Open ${metric.dashboard_name}` : 'Open dashboard'
}
return metric.key.startsWith('insight:') ? 'Open insight' : 'Open as a trend'
@@ -44,16 +44,22 @@ export function TodayPulseCard({
tone,
formatValue,
onOpen,
+ pinned,
+ pinDisabledReason,
+ onTogglePin,
}: {
metric: HighlightMetricApi
tone: TodayTone
formatValue: (value: number) => string
onOpen: () => void
+ pinned: boolean
+ pinDisabledReason?: string
+ onTogglePin: () => void
}): JSX.Element {
const [whyOpen, setWhyOpen] = useState(false)
const previous = metric.previous_value
const peak = pulsePeak(metric)
- const why = pulseWhy(metric)
+ const why = pinned ? 'You keep this number on your home. Change it with Edit.' : pulseWhy(metric)
return (
<div className="flex flex-col gap-3 p-3" data-attr="today-pulse-card">
<div className="flex flex-col gap-0.5">
@@ -122,23 +128,37 @@ export function TodayPulseCard({
) : (
<span />
)}
- {why && (
- <Tooltip>
- <TooltipTrigger
- render={
- <CollapsibleTrigger
- iconOnly
- icon={<IconInfo />}
- className="-me-1.5 text-muted-foreground"
- data-attr="today-pulse-card-why"
- />
- }
- >
- Why you see this
- </TooltipTrigger>
- <TooltipContent>Why you see this</TooltipContent>
- </Tooltip>
- )}
+ <div className="-me-1.5 flex items-center">
+ <Button
+ size="icon-xs"
+ aria-label={pinned ? 'Unpin from your home' : 'Pin to your home'}
+ tooltip={pinned ? 'Unpin from your home' : 'Pin to your home'}
+ aria-pressed={pinned}
+ disabledReason={pinDisabledReason}
+ onClick={onTogglePin}
+ className={pinned ? undefined : 'text-muted-foreground'}
+ data-attr="today-pulse-card-pin"
+ >
+ {pinned ? <IconPinFilled /> : <IconPin />}
+ </Button>
+ {why && (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <CollapsibleTrigger
+ iconOnly
+ icon={<IconInfo />}
+ className="text-muted-foreground"
+ data-attr="today-pulse-card-why"
+ />
+ }
+ >
+ Why you see this
+ </TooltipTrigger>
+ <TooltipContent>Why you see this</TooltipContent>
+ </Tooltip>
+ )}
+ </div>
</div>
{why && (
<CollapsibleContent className="px-0 pb-0">
diff --git a/frontend/src/scenes/project-homepage/today/TodayPulseEditor.tsx b/frontend/src/scenes/project-homepage/today/TodayPulseEditor.tsx
new file mode 100644
index 000000000000..9852e9548250
--- /dev/null
+++ b/frontend/src/scenes/project-homepage/today/TodayPulseEditor.tsx
@@ -0,0 +1,157 @@
+import { useActions, useValues } from 'kea'
+import { useState } from 'react'
+
+import { IconPencil, IconPin, IconPinFilled, IconSearch } from '@posthog/icons'
+import {
+ Button,
+ InputGroup,
+ InputGroupAddon,
+ InputGroupInput,
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+ Text,
+ cn,
+} from '@posthog/quill'
+
+import type { PulsePinApi } from 'products/today/frontend/generated/api.schemas'
+
+import { PULSE_TILES, pulsePinLimitReason, todayHighlightsLogic } from './todayHighlightsLogic'
+
+function PulsePinRow({
+ metric,
+ pinned,
+ disabledReason,
+ onToggle,
+}: {
+ metric: PulsePinApi
+ pinned: boolean
+ disabledReason?: string
+ onToggle: () => void
+}): JSX.Element {
+ return (
+ <li>
+ <Button
+ size="row"
+ left
+ aria-pressed={pinned}
+ disabledReason={disabledReason}
+ onClick={onToggle}
+ className="group/pin w-full aria-pressed:bg-transparent aria-pressed:hover:bg-fill-hover"
+ data-attr="today-pulse-pin"
+ >
+ <span className="min-w-0 flex-1 truncate text-left">{metric.name}</span>
+ {pinned ? (
+ <IconPinFilled className="shrink-0" aria-hidden />
+ ) : (
+ <IconPin
+ className="shrink-0 text-muted-foreground opacity-60 group-hover/pin:opacity-100 group-focus-visible/pin:opacity-100"
+ aria-hidden
+ />
+ )}
+ </Button>
+ </li>
+ )
+}
+
+export function TodayPulseEditor(): JSX.Element {
+ const {
+ pulsePins,
+ pulseTiles,
+ pulseInsightResults,
+ pulseInsightResultsLoading,
+ pulseInsightSearchFailed,
+ pulsePinsUnavailableReason,
+ } = useValues(todayHighlightsLogic)
+ const { togglePulsePin, loadPulseInsightResults, pulseEditorOpened } = useActions(todayHighlightsLogic)
+ const [open, setOpen] = useState(false)
+ const [search, setSearch] = useState('')
+ const [shownOnOpen, setShownOnOpen] = useState<PulsePinApi[]>([])
+
+ const isPinned = (key: string): boolean => pulsePins.some((pinned) => pinned.key === key)
+ const searching = search.trim().length > 0
+ const shownNow = [...shownOnOpen, ...pulsePins.filter((pin) => !shownOnOpen.some((shown) => shown.key === pin.key))]
+ const rows = !searching
+ ? shownNow
+ : pulseInsightResultsLoading || pulseInsightSearchFailed
+ ? []
+ : pulseInsightResults
+
+ return (
+ <Popover
+ open={open}
+ onOpenChange={(next) => {
+ setOpen(next)
+ if (next) {
+ pulseEditorOpened()
+ setShownOnOpen(pulseTiles.map(({ key, name, dashboard_id }) => ({ key, name, dashboard_id })))
+ } else {
+ setSearch('')
+ }
+ }}
+ >
+ <PopoverTrigger
+ render={
+ <Button
+ size="sm"
+ className={cn('TodayPulse__edit', pulseTiles.length === 0 && 'TodayPulse__edit--shown')}
+ aria-label="Edit numbers"
+ data-attr="today-pulse-edit"
+ >
+ <IconPencil />
+ Edit
+ </Button>
+ }
+ />
+ <PopoverContent side="bottom" align="end" sideOffset={6} className="w-72 gap-1 p-1">
+ <InputGroup className="h-7">
+ <InputGroupAddon align="inline-start">
+ <IconSearch className="size-3" />
+ </InputGroupAddon>
+ <InputGroupInput
+ autoFocus
+ placeholder="Search insights to pin"
+ aria-label="Search insights to pin"
+ value={search}
+ onChange={(event) => {
+ setSearch(event.target.value)
+ if (event.target.value.trim()) {
+ loadPulseInsightResults(event.target.value)
+ }
+ }}
+ />
+ </InputGroup>
+ <ul className="m-0 flex max-h-72 list-none flex-col overflow-y-auto scroll-mask-y-4 scroll-py-4 p-0">
+ {rows.map((metric) => {
+ const pinned = isPinned(metric.key)
+ return (
+ <PulsePinRow
+ key={metric.key}
+ metric={metric}
+ pinned={pinned}
+ disabledReason={
+ pulsePinsUnavailableReason ?? pulsePinLimitReason(pulsePins.length, pinned)
+ }
+ onToggle={() => togglePulsePin(metric, 'editor')}
+ />
+ )
+ })}
+ </ul>
+ {searching && rows.length === 0 ? (
+ <Text size="xs" render={<p />} className="m-0 px-2 py-1.5 text-muted-foreground">
+ {pulseInsightResultsLoading
+ ? 'Searching…'
+ : pulseInsightSearchFailed
+ ? "Couldn't search your insights. Try again."
+ : 'No insights you can pin match your search'}
+ </Text>
+ ) : null}
+ {pulsePins.length >= PULSE_TILES ? (
+ <Text size="xs" render={<p />} className="m-0 px-2 py-1.5 text-muted-foreground">
+ {PULSE_TILES} pinned. Unpin one to pin another.
+ </Text>
+ ) : null}
+ </PopoverContent>
+ </Popover>
+ )
+}
diff --git a/frontend/src/scenes/project-homepage/today/TodayPulseHoverCard.tsx b/frontend/src/scenes/project-homepage/today/TodayPulseHoverCard.tsx
index 87aca3233704..5b6412421d6f 100644
--- a/frontend/src/scenes/project-homepage/today/TodayPulseHoverCard.tsx
+++ b/frontend/src/scenes/project-homepage/today/TodayPulseHoverCard.tsx
@@ -1,4 +1,4 @@
-import { type FocusEvent, type ReactNode, useCallback, useRef, useState } from 'react'
+import { type FocusEvent, type ReactNode, useCallback, useEffect, useRef, useState } from 'react'
import { Popover, PopoverContent, PopoverTrigger } from '@posthog/quill'
@@ -10,21 +10,33 @@ const CLOSE_DELAY_MS = 150
export function TodayPulseHoverCard({
children,
card,
- onOpen,
+ onOpenChange,
}: {
children: ReactNode
card: ReactNode
- onOpen: () => void
+ onOpenChange: (open: boolean) => void
}): JSX.Element {
- const [open, setOpen] = useState(false)
- const popupRef = useRef<HTMLDivElement>(null)
- const triggerRef = useCallback((): void => trackPointer(), [])
- const show = (next: boolean): void => {
- setOpen(next)
- if (next) {
- onOpen()
+ const [open, setOpenState] = useState(false)
+ const openRef = useRef(false)
+ const onOpenChangeRef = useRef(onOpenChange)
+ onOpenChangeRef.current = onOpenChange
+ const setOpen = (next: boolean): void => {
+ if (next !== openRef.current) {
+ onOpenChange(next)
}
+ openRef.current = next
+ setOpenState(next)
}
+ useEffect(
+ () => () => {
+ if (openRef.current) {
+ onOpenChangeRef.current(false)
+ }
+ },
+ []
+ )
+ const popupRef = useRef<HTMLDivElement>(null)
+ const triggerRef = useCallback((): void => trackPointer(), [])
return (
<Popover
open={open}
@@ -32,7 +44,7 @@ export function TodayPulseHoverCard({
if (next && details.reason === 'trigger-hover' && !pointerMovedRecently()) {
return
}
- show(next)
+ setOpen(next)
}}
>
<PopoverTrigger
@@ -43,7 +55,7 @@ export function TodayPulseHoverCard({
ref={triggerRef}
render={<div />}
className="TodayPulse__trigger"
- onFocus={() => !open && show(true)}
+ onFocus={() => !open && setOpen(true)}
onBlur={(event: FocusEvent) => {
if (!popupRef.current?.contains(event.relatedTarget as Node | null)) {
setOpen(false)
diff --git a/frontend/src/scenes/project-homepage/today/todayHighlightsLogic.ts b/frontend/src/scenes/project-homepage/today/todayHighlightsLogic.ts
index 1d13085ed034..1c83a82fc8d9 100644
--- a/frontend/src/scenes/project-homepage/today/todayHighlightsLogic.ts
+++ b/frontend/src/scenes/project-homepage/today/todayHighlightsLogic.ts
@@ -2,15 +2,53 @@ import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, redu
import { loaders } from 'kea-loaders'
import posthog from 'posthog-js'
+import { toast } from '@posthog/quill'
+
import { ApiError } from 'lib/api'
import { FEATURE_FLAGS } from 'lib/constants'
import { teamLogic } from 'scenes/teamLogic'
-import { todayHighlightsRetrieve } from 'products/today/frontend/generated/api'
-import type { HighlightItemApi, HighlightMetricApi, HighlightsApi } from 'products/today/frontend/generated/api.schemas'
+import { insightsList } from 'products/product_analytics/frontend/generated/api'
+import {
+ todayHighlightsRetrieve,
+ todayPulsePinsRetrieve,
+ todayPulsePinsUpdate,
+} from 'products/today/frontend/generated/api'
+import type {
+ HighlightItemApi,
+ HighlightMetricApi,
+ HighlightsApi,
+ PulsePinApi,
+} from 'products/today/frontend/generated/api.schemas'
export const HIGHLIGHTS_POLL_MS = 2_000
const HIGHLIGHTS_WAIT_MS = 2_000
+const PULSE_SEARCH_DEBOUNCE_MS = 200
+const PINS_LOAD_RETRY_MS = 5_000
+const PINS_LOAD_RETRIES = 3
+const PIN_SEARCH_RESULTS = 20
+const PINNABLE_DISPLAYS = 'ActionsLineGraph,ActionsBar,ActionsStackedBar,ActionsAreaGraph'
+export const PULSE_TILES = 4
+
+export interface PulsePlaceholderTile extends PulsePinApi {
+ placeholder: 'computing' | 'unavailable'
+}
+
+export type TodayPulseTile = HighlightMetricApi | PulsePlaceholderTile
+
+export function isPlaceholderTile(tile: TodayPulseTile): tile is PulsePlaceholderTile {
+ return 'placeholder' in tile
+}
+
+export type PulsePinSource = 'editor' | 'hover_card'
+
+export function pulsePinLimitReason(pinnedCount: number, pinned: boolean): string | undefined {
+ return pinnedCount >= PULSE_TILES && !pinned ? `You can pin ${PULSE_TILES}. Unpin one first.` : undefined
+}
+
+function pulseKind(key: string): 'insight' | 'key_metric' {
+ return key.startsWith('insight:') ? 'insight' : 'key_metric'
+}
function hiddenHighlightKey(projectId: number | string, key: string): string {
return `${projectId}:${key}`
@@ -28,6 +66,20 @@ export interface todayHighlightsLogicValues {
highlightsLoading: boolean
highlightsPending: boolean
highlightsWaitOver: boolean
+ pulseInsightResults: PulsePinApi[]
+ pulseInsightResultsLoading: boolean
+ pulseInsightSearchFailed: boolean
+ pulseOrderHeld: {
+ keys: string[]
+ owner: string
+ } | null
+ pulsePins: PulsePinApi[]
+ pulsePinsLoadFailed: boolean
+ pulsePinsLoaded: boolean
+ pulsePinsLoading: boolean
+ pulsePinsSaving: boolean
+ pulsePinsUnavailableReason: string | null
+ pulseTiles: TodayPulseTile[]
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -46,6 +98,13 @@ export interface todayHighlightsLogicActions {
item: HighlightItemApi
position: number
}
+ holdPulseOrder: (
+ owner: string,
+ keys: string[]
+ ) => {
+ keys: string[]
+ owner: string
+ }
loadHighlights: () => any
loadHighlightsFailure: (
error: string,
@@ -61,6 +120,47 @@ export interface todayHighlightsLogicActions {
highlights: HighlightsApi | null
payload?: any
}
+ loadPulseInsightResults: (search: string) => string
+ loadPulseInsightResultsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadPulseInsightResultsSuccess: (
+ pulseInsightResults: {
+ dashboard_id: null
+ key: string
+ name: string
+ }[],
+ payload?: string
+ ) => {
+ pulseInsightResults: {
+ dashboard_id: null
+ key: string
+ name: string
+ }[]
+ payload?: string
+ }
+ loadPulsePins: () => any
+ loadPulsePinsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadPulsePinsSuccess: (
+ pulsePins: PulsePinApi[],
+ payload?: any
+ ) => {
+ pulsePins: PulsePinApi[]
+ payload?: any
+ }
+ pulseEditorOpened: () => {
+ value: true
+ }
pulseMetricOpened: (
metric: HighlightMetricApi,
position: number
@@ -75,12 +175,31 @@ export interface todayHighlightsLogicActions {
metric: HighlightMetricApi
position: number
}
+ pulsePinsLoadGaveUp: () => {
+ value: true
+ }
+ pulsePinsSaved: () => {
+ value: true
+ }
+ releasePulseOrder: (owner: string) => {
+ owner: string
+ }
setHiddenHighlights: (hidden: Record<string, string>) => {
hidden: Record<string, string>
}
+ setPinnedPulseKeys: (metrics: PulsePinApi[]) => {
+ metrics: PulsePinApi[]
+ }
stopWaitingForHighlights: () => {
value: true
}
+ togglePulsePin: (
+ pin: PulsePinApi,
+ source: PulsePinSource
+ ) => {
+ pin: PulsePinApi
+ source: PulsePinSource
+ }
unhideHighlight: (
item: HighlightItemApi,
position: number
@@ -93,6 +212,19 @@ export interface todayHighlightsLogicActions {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface todayHighlightsLogicMeta {
__keaTypeGenInternalSelectorTypes: {
+ pulsePinsUnavailableReason: (
+ pulsePinsLoaded: boolean,
+ pulsePinsLoadFailed: boolean,
+ pulsePinsSaving: boolean
+ ) => string | null
+ pulseTiles: (
+ pulsePins: PulsePinApi[],
+ highlights: HighlightsApi | null,
+ pulseOrderHeld: {
+ keys: string[]
+ owner: string
+ } | null
+ ) => TodayPulseTile[]
highlightsPending: (highlights: HighlightsApi | null, highlightsLoading: boolean) => boolean
doneHighlightKeys: (
highlights: HighlightsApi | null,
@@ -129,8 +261,54 @@ export const todayHighlightsLogic = kea<todayHighlightsLogicType>([
unhideHighlight: (item: HighlightItemApi, position: number) => ({ item, position }),
setHiddenHighlights: (hidden: Record<string, string>) => ({ hidden }),
stopWaitingForHighlights: true,
+ setPinnedPulseKeys: (metrics: PulsePinApi[]) => ({ metrics }),
+ pulsePinsSaved: true,
+ pulseEditorOpened: true,
+ togglePulsePin: (pin: PulsePinApi, source: PulsePinSource) => ({ pin, source }),
+ holdPulseOrder: (owner: string, keys: string[]) => ({ owner, keys }),
+ releasePulseOrder: (owner: string) => ({ owner }),
+ pulsePinsLoadGaveUp: true,
}),
- loaders(({ values }) => ({
+ loaders(({ values, cache }) => ({
+ pulseInsightResults: [
+ [] as PulsePinApi[],
+ {
+ loadPulseInsightResults: async (search: string, breakpoint) => {
+ await breakpoint(PULSE_SEARCH_DEBOUNCE_MS)
+ const { results } = await insightsList(String(values.currentProjectId), {
+ basic: true,
+ saved: true,
+ display: PINNABLE_DISPLAYS,
+ search,
+ order: '-last_viewed_at',
+ limit: PIN_SEARCH_RESULTS,
+ })
+ breakpoint()
+ return results.map((insight) => ({
+ key: `insight:${insight.short_id}`,
+ name: insight.name || insight.derived_name || 'Untitled insight',
+ dashboard_id: null,
+ }))
+ },
+ },
+ ],
+ pulsePins: [
+ [] as PulsePinApi[],
+ {
+ loadPulsePins: async (): Promise<PulsePinApi[]> => {
+ const edits = cache.pinEdits ?? 0
+ try {
+ const { pins } = await todayPulsePinsRetrieve(String(values.currentProjectId))
+ return (cache.pinEdits ?? 0) === edits ? pins : values.pulsePins
+ } catch (error) {
+ if (error instanceof ApiError && error.status === 404) {
+ return []
+ }
+ throw error
+ }
+ },
+ },
+ ],
highlights: [
null as HighlightsApi | null,
{
@@ -151,6 +329,23 @@ export const todayHighlightsLogic = kea<todayHighlightsLogicType>([
],
})),
reducers({
+ pulsePins: {
+ setPinnedPulseKeys: (_, { metrics }) => metrics,
+ },
+ pulsePinsLoaded: [false, { loadPulsePinsSuccess: () => true }],
+ pulsePinsLoadFailed: [false, { pulsePinsLoadGaveUp: () => true, loadPulsePinsSuccess: () => false }],
+ pulsePinsSaving: [false, { setPinnedPulseKeys: () => true, pulsePinsSaved: () => false }],
+ pulseInsightSearchFailed: [
+ false,
+ { loadPulseInsightResults: () => false, loadPulseInsightResultsFailure: () => true },
+ ],
+ pulseOrderHeld: [
+ null as { owner: string; keys: string[] } | null,
+ {
+ holdPulseOrder: (_, { owner, keys }) => ({ owner, keys }),
+ releasePulseOrder: (state, { owner }) => (state?.owner === owner ? null : state),
+ },
+ ],
hiddenHighlights: [
{} as Record<string, string>,
{ persist: true },
@@ -176,6 +371,49 @@ export const todayHighlightsLogic = kea<todayHighlightsLogicType>([
},
}),
selectors({
+ pulsePinsUnavailableReason: [
+ (s) => [s.pulsePinsLoaded, s.pulsePinsLoadFailed, s.pulsePinsSaving],
+ (pulsePinsLoaded: boolean, pulsePinsLoadFailed: boolean, pulsePinsSaving: boolean): string | null =>
+ pulsePinsSaving
+ ? 'Saving your pins…'
+ : pulsePinsLoadFailed
+ ? "Couldn't load your pins. Reload the page to try again."
+ : pulsePinsLoaded
+ ? null
+ : 'Loading your pins…',
+ ],
+ pulseTiles: [
+ (s) => [s.pulsePins, s.highlights, s.pulseOrderHeld],
+ (
+ pulsePins: PulsePinApi[],
+ highlights: HighlightsApi | null,
+ pulseOrderHeld: { owner: string; keys: string[] } | null
+ ): TodayPulseTile[] => {
+ const suggested = (highlights?.pulse ?? []).filter(
+ (metric) => !pulsePins.some((pin) => pin.key === metric.key)
+ )
+ const pinned: TodayPulseTile[] = pulsePins.map(
+ (pinned) =>
+ highlights?.pulse.find((metric) => metric.key === pinned.key) ?? {
+ ...pinned,
+ placeholder:
+ highlights?.pins.find((pin) => pin.key === pinned.key)?.status === 'unavailable'
+ ? 'unavailable'
+ : 'computing',
+ }
+ )
+ const tiles = [...pinned, ...suggested].slice(0, PULSE_TILES)
+ if (!pulseOrderHeld) {
+ return tiles
+ }
+ const held = pulseOrderHeld.keys
+ const place = (key: string): number => {
+ const index = held.indexOf(key)
+ return index === -1 ? held.length : index
+ }
+ return [...tiles].sort((a, b) => place(a.key) - place(b.key))
+ },
+ ],
highlightsPending: [
(s) => [s.highlights, s.highlightsLoading],
(highlights: HighlightsApi | null, highlightsLoading: boolean): boolean =>
@@ -209,6 +447,49 @@ export const todayHighlightsLogic = kea<todayHighlightsLogicType>([
],
}),
listeners(({ actions, values, cache }) => ({
+ setPinnedPulseKeys: async ({ metrics }, breakpoint) => {
+ cache.pinEdits = (cache.pinEdits ?? 0) + 1
+ const previous: Promise<unknown> = cache.pinsSave ?? Promise.resolve()
+ const save = (cache.pinsSave = previous
+ .catch(() => undefined)
+ .then(() => todayPulsePinsUpdate(String(values.currentProjectId), { pins: metrics })))
+ try {
+ await save
+ } catch {
+ actions.pulsePinsSaved()
+ toast.error({ title: "Couldn't save your numbers. Try again." })
+ breakpoint()
+ actions.loadPulsePins()
+ actions.loadHighlights()
+ return
+ }
+ actions.pulsePinsSaved()
+ breakpoint()
+ actions.loadHighlights()
+ },
+ togglePulsePin: ({ pin, source }) => {
+ if (values.pulsePinsUnavailableReason) {
+ return
+ }
+ const pinned = values.pulsePins.some((existing) => existing.key === pin.key)
+ const pinnedCountBefore = values.pulsePins.length
+ if (pulsePinLimitReason(pinnedCountBefore, pinned)) {
+ return
+ }
+ actions.setPinnedPulseKeys(
+ pinned
+ ? values.pulsePins.filter((existing) => existing.key !== pin.key)
+ : [...values.pulsePins, { key: pin.key, name: pin.name, dashboard_id: pin.dashboard_id ?? null }]
+ )
+ posthog.capture(pinned ? 'today pulse number unpinned' : 'today pulse number pinned', {
+ kind: pulseKind(pin.key),
+ source,
+ pinned_count_before: pinnedCountBefore,
+ })
+ },
+ pulseEditorOpened: () => {
+ posthog.capture('today pulse editor opened', { kept_count: values.pulsePins.length })
+ },
hideHighlight: ({ item, position }) => {
const day = values.highlights?.day
if (!day) {
@@ -245,7 +526,7 @@ export const todayHighlightsLogic = kea<todayHighlightsLogicType>([
},
pulseMetricOpened: ({ metric, position }) => {
posthog.capture('today pulse metric opened', {
- kind: metric.key.startsWith('insight:') ? 'insight' : 'key_metric',
+ kind: pulseKind(metric.key),
reason: metric.reason,
position,
pulse_ranking: posthog.getFeatureFlag(FEATURE_FLAGS.TODAY_PULSE_RANKING) ?? null,
@@ -258,12 +539,26 @@ export const todayHighlightsLogic = kea<todayHighlightsLogicType>([
}
previewed.add(metric.key)
posthog.capture('today pulse metric previewed', {
- kind: metric.key.startsWith('insight:') ? 'insight' : 'key_metric',
+ kind: pulseKind(metric.key),
reason: metric.reason,
position,
pulse_ranking: posthog.getFeatureFlag(FEATURE_FLAGS.TODAY_PULSE_RANKING) ?? null,
})
},
+ loadPulsePinsSuccess: () => {
+ cache.pinsLoadRetries = 0
+ },
+ loadPulsePinsFailure: () => {
+ if ((cache.pinsLoadRetries ?? 0) >= PINS_LOAD_RETRIES) {
+ actions.pulsePinsLoadGaveUp()
+ return
+ }
+ cache.pinsLoadRetries = (cache.pinsLoadRetries ?? 0) + 1
+ cache.disposables.add(() => {
+ const retry = window.setTimeout(() => actions.loadPulsePins(), PINS_LOAD_RETRY_MS)
+ return () => clearTimeout(retry)
+ }, 'pulsePinsLoadRetry')
+ },
loadHighlightsSuccess: ({ highlights }) => {
if (!highlights) {
return
@@ -275,6 +570,10 @@ export const todayHighlightsLogic = kea<todayHighlightsLogicType>([
}, 'highlightsPoll')
return
}
+ if (cache.highlightsLoadedCaptured) {
+ return
+ }
+ cache.highlightsLoadedCaptured = true
posthog.capture('today highlights loaded', {
status: highlights.status,
item_count: highlights.items.length,
@@ -282,6 +581,7 @@ export const todayHighlightsLogic = kea<todayHighlightsLogicType>([
opportunity_count: highlights.items.filter((item) => item.label === 'opportunity').length,
sources: highlights.items.map((item) => item.source),
pulse_count: highlights.pulse.length,
+ pinned_count: highlights.pins.length,
pulse_reasons: highlights.pulse.map((metric) => metric.reason),
pulse_ranking: posthog.getFeatureFlag(FEATURE_FLAGS.TODAY_PULSE_RANKING) ?? null,
})
@@ -289,6 +589,7 @@ export const todayHighlightsLogic = kea<todayHighlightsLogicType>([
})),
afterMount(({ actions, cache }) => {
actions.loadHighlights()
+ actions.loadPulsePins()
cache.disposables.add(() => {
const timer = window.setTimeout(() => actions.stopWaitingForHighlights(), HIGHLIGHTS_WAIT_MS)
return () => clearTimeout(timer)
diff --git a/frontend/src/scenes/project-homepage/today/todayTestFixtures.ts b/frontend/src/scenes/project-homepage/today/todayTestFixtures.ts
index 22fce3c75a6b..ab526b3f65c8 100644
--- a/frontend/src/scenes/project-homepage/today/todayTestFixtures.ts
+++ b/frontend/src/scenes/project-homepage/today/todayTestFixtures.ts
@@ -54,6 +54,7 @@ export function makePulseMetric(overrides: Partial<HighlightMetricApi> = {}): Hi
period_starts: ['2026-09-21', '2026-09-28'],
reason: 'routine',
dashboard_name: null,
+ dashboard_id: null,
opened_days: 5,
last_opened: '2026-09-29',
movers: [],
@@ -70,6 +71,7 @@ export function makeHighlights(overrides: Partial<HighlightsApi> = {}): Highligh
refresh_at: '2026-10-01T00:00:00Z',
pulse: [],
items: [],
+ pins: [],
...overrides,
}
}
diff --git a/products/dashboards/backend/facade/api.py b/products/dashboards/backend/facade/api.py
index 230df7a7280b..ad0fef74df14 100644
--- a/products/dashboards/backend/facade/api.py
+++ b/products/dashboards/backend/facade/api.py
@@ -118,11 +118,24 @@ def home_dashboard_insights(*, team: "Team", user: User, limit: int) -> Dashboar
def dashboard_insights(*, team: "Team", user: User, dashboard_id: int, limit: int) -> DashboardInsights | None:
+ return _dashboard_insights(team, user, dashboard_id, limit)
+
+
+def dashboard_insight_tile(*, team: "Team", user: User, dashboard_id: int, short_id: str) -> DashboardInsights | None:
+ found = _dashboard_insights(team, user, dashboard_id, 1, short_id=short_id)
+ return found if found is not None and found.tiles else None
+
+
+def _dashboard_insights(
+ team: "Team", user: User, dashboard_id: int, limit: int, short_id: str | None = None
+) -> DashboardInsights | None:
dashboard = Dashboard.objects.filter(team_id=team.id, pk=dashboard_id).first()
access = UserAccessControl(user=user, team=team)
if dashboard is None or not access.check_access_level_for_object(dashboard, "viewer"):
return None
insight_tiles = DashboardTile.objects.filter(dashboard=dashboard, insight__isnull=False, insight__deleted=False)
+ if short_id is not None:
+ insight_tiles = insight_tiles.filter(insight__short_id=short_id)
tiles = DashboardTile.sort_tiles_by_layout(insight_tiles.select_related("insight"))
return DashboardInsights(
dashboard_id=dashboard.id,
diff --git a/products/product_analytics/backend/facade/api.py b/products/product_analytics/backend/facade/api.py
index f0632e2a051e..9b234cddf0f6 100644
--- a/products/product_analytics/backend/facade/api.py
+++ b/products/product_analytics/backend/facade/api.py
@@ -236,7 +236,12 @@ def save_saved_insight_query(
def get_insight_series(
- *, team: Team, user: User, short_id: str, dashboard: InsightDashboardContext | None = None
+ *,
+ team: Team,
+ user: User,
+ short_id: str,
+ dashboard: InsightDashboardContext | None = None,
+ blocking: bool = False,
) -> InsightSeries | None:
insight = Insight.objects.filter(team__project_id=team.project_id, short_id=short_id, deleted=False).first()
if insight is None:
@@ -249,5 +254,11 @@ def get_insight_series(
)
return insight_series.insight_series(
- team, user, short_id=insight.short_id, name=insight.name, query=insight.query or {}, dashboard=dashboard
+ team,
+ user,
+ short_id=insight.short_id,
+ name=insight.name,
+ query=insight.query or {},
+ dashboard=dashboard,
+ blocking=blocking,
)
diff --git a/products/product_analytics/backend/insight_series.py b/products/product_analytics/backend/insight_series.py
index e8063bbf190e..e188489f686e 100644
--- a/products/product_analytics/backend/insight_series.py
+++ b/products/product_analytics/backend/insight_series.py
@@ -33,6 +33,7 @@ NO_BREAKDOWN_VALUE = "[No value]"
LOOKBACK = {"day": "-56d", "week": "-16w", "month": "-24m"}
DATE_FILTERS = ("date_from", "date_to", "explicitDate", "interval", "compareFilter")
EXECUTION_MODE = ExecutionMode.RECENT_CACHE_CALCULATE_ASYNC_IF_STALE
+BLOCKING_EXECUTION_MODE = ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE
def _run(
@@ -41,6 +42,7 @@ def _run(
source: dict[str, Any],
filters: dict[str, Any] | None,
variables: dict[str, Any] | None,
+ blocking: bool = False,
) -> dict[str, Any]:
from posthog.api.services.query import process_query_dict # noqa: PLC0415
@@ -49,7 +51,7 @@ def _run(
source,
dashboard_filters_json=filters,
variables_override_json=variables,
- execution_mode=EXECUTION_MODE,
+ execution_mode=BLOCKING_EXECUTION_MODE if blocking else EXECUTION_MODE,
user=user,
)
return response.model_dump() if isinstance(response, BaseModel) else response
@@ -114,13 +116,14 @@ def _sql_series(
query: dict[str, Any],
filters: dict[str, Any],
variables: dict[str, Any] | None,
+ blocking: bool = False,
) -> InsightSeries | None:
settings = query.get("chartSettings") or {}
x_column = (settings.get("xAxis") or {}).get("column")
y_axes = [axis for axis in settings.get("yAxis") or [] if axis.get("column")]
if query.get("display") not in CHARTED_SQL_DISPLAYS or not x_column or not y_axes:
return None
- response = _run(team, user, query["source"], filters, variables)
+ response = _run(team, user, query["source"], filters, variables, blocking)
if response.get("hasMore"):
return None
position = {column: index for index, column in enumerate(response.get("columns") or [])}
@@ -188,6 +191,7 @@ def insight_series(
name: str | None,
query: dict[str, Any],
dashboard: InsightDashboardContext | None,
+ blocking: bool = False,
) -> InsightSeries | None:
dashboard_filters: dict[str, Any] = {}
variables: dict[str, Any] | None = None
@@ -199,7 +203,16 @@ def insight_series(
filters = {key: value for key, value in dashboard_filters.items() if key not in DATE_FILTERS}
source = query.get("source", query)
if query.get("kind") == "DataVisualizationNode" and source.get("kind") == "HogQLQuery":
- return _sql_series(team, user, short_id=short_id, name=name, query=query, filters=filters, variables=variables)
+ return _sql_series(
+ team,
+ user,
+ short_id=short_id,
+ name=name,
+ query=query,
+ filters=filters,
+ variables=variables,
+ blocking=blocking,
+ )
trends = source.get("trendsFilter") or {}
if source.get("kind") != "TrendsQuery" or trends.get("display") in UNCHARTED_DISPLAYS:
return None
@@ -216,7 +229,7 @@ def insight_series(
dateRange={**kept, "date_from": LOOKBACK[interval], "excludeIncompletePeriods": True},
trendsFilter={**{k: v for k, v in trends.items() if k != "smoothingIntervals"}, "metricShowChange": False},
)
- response = _run(team, user, bounded, filters, variables)
+ response = _run(team, user, bounded, filters, variables, blocking)
formula = bool(trends.get("formula") or trends.get("formulas") or trends.get("formulaNodes"))
several = len(source.get("series") or []) > 1
series: dict[str, list[tuple[date, float]]] = {}
diff --git a/products/product_analytics/backend/presentation/insight.py b/products/product_analytics/backend/presentation/insight.py
index cf1a344f9ec8..bc6607ac92b7 100644
--- a/products/product_analytics/backend/presentation/insight.py
+++ b/products/product_analytics/backend/presentation/insight.py
@@ -1888,6 +1888,20 @@ class InsightDataChecksSerializer(serializers.Serializer):
)
+def chart_display_filter(value: str) -> Q:
+ displays = [display for display in value.split(",") if display]
+ unknown = set(displays) - {display.value for display in schema.ChartDisplayType}
+ if not displays or unknown:
+ raise ValidationError({"display": f"Unknown chart types: {', '.join(sorted(unknown)) or value!r}."})
+ trends_display = Q(query__source__trendsFilter__display__in=displays)
+ if schema.ChartDisplayType.ACTIONS_LINE_GRAPH in displays:
+ trends_display |= Q(query__source__trendsFilter__display__isnull=True)
+ return (
+ Q(query__kind=schema.NodeKind.INSIGHT_VIZ_NODE, query__source__kind=schema.NodeKind.TRENDS_QUERY)
+ & trends_display
+ ) | Q(query__kind=schema.NodeKind.DATA_VISUALIZATION_NODE, query__display__in=displays)
+
+
@extend_schema(extensions={"x-product": ProductKey.PRODUCT_ANALYTICS})
@extend_schema_view(
list=extend_schema(
@@ -1963,6 +1977,15 @@ Background calculation can be tracked using the `query_status` response field.""
type=OpenApiTypes.BOOL,
description="Exclude Business intelligence worksheets from the insight list.",
),
+ OpenApiParameter(
+ name="display",
+ type=OpenApiTypes.STR,
+ description=(
+ "Comma-separated chart types, e.g. `ActionsLineGraph,ActionsBar`. Only returns trends and SQL "
+ "insights shown as one of them. A trends insight with no chart type set counts as "
+ "`ActionsLineGraph`."
+ ),
+ ),
OpenApiParameter(
name="order",
type=OpenApiTypes.STR,
@@ -2377,6 +2400,8 @@ class InsightViewSet(
)
else:
queryset = queryset.filter(legacy_filter)
+ elif key == "display":
+ queryset = queryset.filter(chart_display_filter(request.GET["display"]))
elif key == "search":
term = request.GET["search"]
if len(term) > MAX_SEARCH_LENGTH:
diff --git a/products/product_analytics/backend/tests/api/test_insight.py b/products/product_analytics/backend/tests/api/test_insight.py
index dcedca89bf43..ec5428bedce7 100644
--- a/products/product_analytics/backend/tests/api/test_insight.py
+++ b/products/product_analytics/backend/tests/api/test_insight.py
@@ -74,6 +74,7 @@ from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile, Text
from products.product_analytics.backend.facade.models import Insight, InsightVariable
from products.product_analytics.backend.models.insight import InsightViewed
+from products.product_analytics.backend.presentation.insight import chart_display_filter
from products.subscriptions.backend.facade.testing import (
create_subscription,
create_subscription_delivery,
@@ -1262,6 +1263,47 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
self.assertEqual(len(response.json()["results"]), 2)
+ @parameterized.expand(
+ [
+ ("line graphs", "ActionsLineGraph", ["no display", "line", "sql line"]),
+ ("several chart types", "ActionsBar,ActionsPie", ["bar", "pie"]),
+ ("a chart type no insight uses", "WorldMap", []),
+ ]
+ )
+ def test_filtering_insights_by_chart_type(self, _name: str, display: str, expected: list[str]) -> None:
+ trends = [
+ ("no display", {}),
+ ("line", {"trendsFilter": {"display": "ActionsLineGraph"}}),
+ ("bar", {"trendsFilter": {"display": "ActionsBar"}}),
+ ("pie", {"trendsFilter": {"display": "ActionsPie"}}),
+ ]
+ for name, query in [
+ *(
+ (name, {"kind": "InsightVizNode", "source": {"kind": "TrendsQuery", "series": [], **chart}})
+ for name, chart in trends
+ ),
+ (
+ "sql line",
+ {
+ "kind": "DataVisualizationNode",
+ "display": "ActionsLineGraph",
+ "source": {"kind": "HogQLQuery", "query": "select 1"},
+ },
+ ),
+ ("sql table", {"kind": "DataVisualizationNode", "source": {"kind": "HogQLQuery", "query": "select 1"}}),
+ ("funnel", {"kind": "InsightVizNode", "source": {"kind": "FunnelsQuery", "series": []}}),
+ ]:
+ Insight.objects.create(team=self.team, name=name, query=query)
+
+ found = Insight.objects.filter(team=self.team).filter(chart_display_filter(display))
+
+ assert sorted(insight.name for insight in found) == sorted(expected)
+
+ def test_listing_insights_by_an_unknown_chart_type_is_rejected(self) -> None:
+ response = self.client.get(f"/api/environments/{self.team.pk}/insights/?display=ActionsLineGraph,Sparkles")
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
def test_listing_insights_by_journeys_type(self) -> None:
journeys_insight_id, _ = self.dashboard_api.create_insight(
data={"query": {"kind": "InsightVizNode", "source": {"kind": "PathsV2Query"}}}
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index a21ca2f25b3a..60c34ef60898 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -9608,6 +9608,10 @@ export type InsightsListParams = {
* Filter by `last_modified_at < date_to`. Accepts absolute dates or relative strings.
*/
date_to?: string
+ /**
+ * Comma-separated chart types, e.g. `ActionsLineGraph,ActionsBar`. Only returns trends and SQL insights shown as one of them. A trends insight with no chart type set counts as `ActionsLineGraph`.
+ */
+ display?: string
/**
* Exclude Business intelligence worksheets from the insight list.
*/
diff --git a/products/today/backend/facade/api.py b/products/today/backend/facade/api.py
index c244a2e7689d..46fe985f956b 100644
--- a/products/today/backend/facade/api.py
+++ b/products/today/backend/facade/api.py
@@ -12,6 +12,7 @@ from ..logic import (
code_excerpts,
figure_sources,
highlights,
+ pulse_pins,
report_page as report_pages,
)
from ..logic.jev import GatewayJev
@@ -53,3 +54,11 @@ def report_figure_marks(*, team: Team, user: User, report_id: str) -> list[contr
def get_highlights(*, team: Team, user: User, scopes: frozenset[str] | None) -> contracts.Highlights:
return highlights.get_highlights(team=team, user=user, scopes=scopes)
+
+
+def get_pulse_pins(*, team: Team, user: User, scopes: frozenset[str] | None) -> contracts.PulsePins:
+ return contracts.PulsePins(pins=pulse_pins.get_pins(team=team, user_id=user.id, scopes=scopes))
+
+
+def set_pulse_pins(*, team: Team, user: User, pins: list[contracts.PulsePin]) -> contracts.PulsePins:
+ return contracts.PulsePins(pins=pulse_pins.set_pins(team=team, user_id=user.id, pins=pins))
diff --git a/products/today/backend/facade/contracts.py b/products/today/backend/facade/contracts.py
index 9091ae298b23..e9f26052b63e 100644
--- a/products/today/backend/facade/contracts.py
+++ b/products/today/backend/facade/contracts.py
@@ -16,6 +16,7 @@ from .enums import (
HighlightInterval,
HighlightLabel,
HighlightMetricReason,
+ HighlightPinStatus,
HighlightPriority,
HighlightsStatus,
HighlightUnit,
@@ -186,6 +187,7 @@ class HighlightMetric:
period_starts: list[date] = field(default_factory=list)
reason: HighlightMetricReason | None = None
dashboard_name: str | None = None
+ dashboard_id: int | None = None
opened_days: int | None = None
last_opened: date | None = None
movers: list[HighlightMover] = field(default_factory=list)
@@ -205,6 +207,24 @@ class HighlightItem:
score: float
+@dataclass(frozen=True)
+class PulsePin:
+ key: str
+ name: str
+ dashboard_id: int | None = None
+
+
+@dataclass(frozen=True)
+class PulsePins:
+ pins: list[PulsePin]
+
+
+@dataclass(frozen=True)
+class HighlightPin:
+ key: str
+ status: HighlightPinStatus
+
+
@dataclass(frozen=True)
class Highlights:
status: HighlightsStatus
@@ -213,6 +233,7 @@ class Highlights:
refresh_at: datetime
pulse: list[HighlightMetric]
items: list[HighlightItem]
+ pins: list[HighlightPin] = field(default_factory=list)
class DailyValueNotReady(Exception):
diff --git a/products/today/backend/facade/enums.py b/products/today/backend/facade/enums.py
index c977520a276a..14e114bb2006 100644
--- a/products/today/backend/facade/enums.py
+++ b/products/today/backend/facade/enums.py
@@ -59,6 +59,11 @@ class HighlightMetricReason(LabeledStrEnum):
KEY_METRIC = "key_metric", "Project key metric"
+class HighlightPinStatus(LabeledStrEnum):
+ READY = "ready", "Ready"
+ UNAVAILABLE = "unavailable", "Unavailable"
+
+
class HighlightInterval(LabeledStrEnum):
DAY = "day", "Day"
WEEK = "week", "Week"
diff --git a/products/today/backend/facade/temporal.py b/products/today/backend/facade/temporal.py
index 7c75e0cc82e5..0ca9c0c6ed59 100644
--- a/products/today/backend/facade/temporal.py
+++ b/products/today/backend/facade/temporal.py
@@ -4,9 +4,13 @@ activities and schedule."""
from collections.abc import Callable
from typing import Any
-from ..temporal.activities import finalize_highlights_activity, run_highlight_source_activity
+from ..temporal.activities import finalize_highlights_activity, resolve_pins_activity, run_highlight_source_activity
from ..temporal.schedule import delete_today_briefing_schedule as delete_today_briefing_schedule
from ..temporal.workflows import ComputeTodayHighlightsWorkflow
WORKFLOWS = [ComputeTodayHighlightsWorkflow]
-ACTIVITIES: list[Callable[..., Any]] = [run_highlight_source_activity, finalize_highlights_activity]
+ACTIVITIES: list[Callable[..., Any]] = [
+ run_highlight_source_activity,
+ resolve_pins_activity,
+ finalize_highlights_activity,
+]
diff --git a/products/today/backend/logic/highlight_sources/key_metrics.py b/products/today/backend/logic/highlight_sources/key_metrics.py
index dd42846a1de6..e3161085b077 100644
--- a/products/today/backend/logic/highlight_sources/key_metrics.py
+++ b/products/today/backend/logic/highlight_sources/key_metrics.py
@@ -25,10 +25,10 @@ def find(context: Context) -> Found:
raise DailyValueNotReady("key_metrics")
shown = [metric for metric in metrics if metric.this_week or metric.last_week]
candidates = [candidate for metric in shown if (candidate := _same_weekday(context, metric)) is not None]
- return Found(items=tuple(candidates), pulse=tuple(_tile(metric) for metric in shown))
+ return Found(items=tuple(candidates), pulse=tuple(tile(metric) for metric in shown))
-def _tile(metric: KeyMetric) -> contracts.HighlightMetric:
+def tile(metric: KeyMetric) -> contracts.HighlightMetric:
return contracts.HighlightMetric(
key=metric.key,
name=metric.name,
diff --git a/products/today/backend/logic/highlight_sources/routine.py b/products/today/backend/logic/highlight_sources/routine.py
index 13a25bded278..eba2df707bab 100644
--- a/products/today/backend/logic/highlight_sources/routine.py
+++ b/products/today/backend/logic/highlight_sources/routine.py
@@ -8,7 +8,12 @@ from posthog.dataclasses import frozen
from posthog.models import FileSystemViewLog
from posthog.models.file_system.file_system_view_log import VIEW_DAYS_KEPT
-from products.dashboards.backend.facade.api import dashboard_insights
+from products.dashboards.backend.facade.api import (
+ DashboardInsights,
+ DashboardInsightTile,
+ dashboard_insight_tile,
+ dashboard_insights,
+)
from products.product_analytics.backend.facade.api import get_insight_series
from products.product_analytics.backend.facade.contracts import InsightDashboardContext
@@ -45,16 +50,20 @@ class ViewedItem:
def find(context: Context) -> Found:
+ pinned = context.pinned
+ budget = FRECENCY_TILES - len(pinned)
ranking = pulse_ranking(context.user, context.team)
if ranking in (FRECENCY_RANKING, RECENCY_RANKING):
- return Found(pulse=tuple(_frecent_metrics(context, ranking)))
+ return Found(pulse=tuple(_frecent_metrics(context, ranking, pinned, budget)))
metrics: list[contracts.HighlightMetric] = []
for item in _routine_insights(context):
- metric = context.guard(f"routine {item.ref}", partial(_metric, context, item.ref, viewed=item), None)
+ if len(metrics) >= min(ROUTINE_TILES, budget):
+ break
+ if f"insight:{item.ref}" in pinned:
+ continue
+ metric = context.guard(f"routine {item.ref}", partial(insight_metric, context, item.ref, viewed=item), None)
if metric is not None:
metrics.append(metric)
- if len(metrics) == ROUTINE_TILES:
- break
return Found(pulse=tuple(metrics))
@@ -97,15 +106,17 @@ def frecency(view_days: Collection[date], today: date) -> float:
return sum(0.5 ** (age / FRECENCY_HALF_LIFE_DAYS) for age in ages if 0 <= age <= FRECENCY_LOOKBACK_DAYS)
-def _frecent_metrics(context: Context, ranking: str) -> list[contracts.HighlightMetric]:
+def _frecent_metrics(
+ context: Context, ranking: str, excluded: Collection[str], budget: int
+) -> list[contracts.HighlightMetric]:
metrics: list[contracts.HighlightMetric] = []
for item in _frecent_views(context, ranking)[:FRECENCY_CANDIDATES]:
- shown = frozenset(metric.key for metric in metrics)
+ if len(metrics) >= budget:
+ break
+ shown = frozenset([*excluded, *(metric.key for metric in metrics)])
metric = context.guard(f"frecent {item.kind} {item.ref}", partial(_frecent_metric, context, item, shown), None)
if metric is not None:
metrics.append(metric)
- if len(metrics) == FRECENCY_TILES:
- break
return metrics
@@ -131,7 +142,7 @@ def _frecent_views(context: Context, ranking: str) -> list[ViewedItem]:
def _frecent_metric(context: Context, item: ViewedItem, shown: frozenset[str]) -> contracts.HighlightMetric | None:
if item.kind == "insight":
- return None if f"insight:{item.ref}" in shown else _metric(context, item.ref, viewed=item)
+ return None if f"insight:{item.ref}" in shown else insight_metric(context, item.ref, viewed=item)
if not item.ref.isdigit():
return None
dashboard = dashboard_insights(
@@ -144,17 +155,7 @@ def _frecent_metric(context: Context, item: ViewedItem, shown: frozenset[str]) -
continue
metric = context.guard(
f"dashboard {item.ref} tile {tile.insight_short_id}",
- partial(
- _metric,
- context,
- tile.insight_short_id,
- dashboard=InsightDashboardContext(
- filters=dashboard.filters, tile_filters=tile.filters_overrides, variables=dashboard.variables
- ),
- viewed=item,
- url=f"/dashboard/{dashboard.dashboard_id}",
- dashboard_name=dashboard.name,
- ),
+ partial(_tile_metric, context, dashboard, tile, viewed=item),
None,
)
if metric is not None:
@@ -162,7 +163,40 @@ def _frecent_metric(context: Context, item: ViewedItem, shown: frozenset[str]) -
return None
-def _metric(
+def dashboard_tile_metric(
+ context: Context, dashboard_id: int, short_id: str, *, blocking: bool = False
+) -> contracts.HighlightMetric | None:
+ dashboard = dashboard_insight_tile(
+ team=context.team, user=context.user, dashboard_id=dashboard_id, short_id=short_id
+ )
+ if dashboard is None:
+ return None
+ return _tile_metric(context, dashboard, dashboard.tiles[0], blocking=blocking)
+
+
+def _tile_metric(
+ context: Context,
+ dashboard: DashboardInsights,
+ tile: DashboardInsightTile,
+ *,
+ viewed: ViewedItem | None = None,
+ blocking: bool = False,
+) -> contracts.HighlightMetric | None:
+ return insight_metric(
+ context,
+ tile.insight_short_id,
+ dashboard=InsightDashboardContext(
+ filters=dashboard.filters, tile_filters=tile.filters_overrides, variables=dashboard.variables
+ ),
+ viewed=viewed,
+ url=f"/dashboard/{dashboard.dashboard_id}",
+ dashboard_name=dashboard.name,
+ dashboard_id=dashboard.dashboard_id,
+ blocking=blocking,
+ )
+
+
+def insight_metric(
context: Context,
short_id: str,
*,
@@ -170,8 +204,12 @@ def _metric(
dashboard: InsightDashboardContext | None = None,
url: str | None = None,
dashboard_name: str | None = None,
+ dashboard_id: int | None = None,
+ blocking: bool = False,
) -> contracts.HighlightMetric | None:
- insight = get_insight_series(team=context.team, user=context.user, short_id=short_id, dashboard=dashboard)
+ insight = get_insight_series(
+ team=context.team, user=context.user, short_id=short_id, dashboard=dashboard, blocking=blocking
+ )
if insight is None:
return None
series = usable_series(insight, context.today)
@@ -216,6 +254,7 @@ def _metric(
value_format=value_format,
reason=HighlightMetricReason.ROUTINE if dashboard is None else HighlightMetricReason.DASHBOARD,
dashboard_name=dashboard_name,
+ dashboard_id=dashboard_id,
opened_days=_opened_days(viewed, context.today) if viewed else None,
last_opened=max(viewed.days) if viewed and viewed.days else None,
movers=_movers(series, insight.averaged_series, period, context.today),
diff --git a/products/today/backend/logic/highlight_types.py b/products/today/backend/logic/highlight_types.py
index 68ca6c3e4282..ab2924f46dfe 100644
--- a/products/today/backend/logic/highlight_types.py
+++ b/products/today/backend/logic/highlight_types.py
@@ -50,11 +50,19 @@ def property_restrictions(team: Team, user: User) -> str:
class Context:
"""Today's `HighlightContext`. A source sees only the protocol, so these internals stay private."""
- def __init__(self, team: Team, user: User, today: date, scopes: frozenset[str] | None = None) -> None:
+ def __init__(
+ self,
+ team: Team,
+ user: User,
+ today: date,
+ scopes: frozenset[str] | None = None,
+ pinned: frozenset[str] = frozenset(),
+ ) -> None:
self.team = team
self.user = user
self.today = today
self.scopes = scopes
+ self.pinned = pinned
self.failures: list[str] = []
self.access = UserAccessControl(user=user, team=team)
diff --git a/products/today/backend/logic/highlights.py b/products/today/backend/logic/highlights.py
index e90d48239f7f..19f435289262 100644
--- a/products/today/backend/logic/highlights.py
+++ b/products/today/backend/logic/highlights.py
@@ -5,6 +5,7 @@ from contextlib import suppress
from dataclasses import replace
from datetime import date, datetime, time, timedelta
from functools import partial
+from uuid import UUID
from django.conf import settings
from django.core.cache import cache
@@ -23,7 +24,7 @@ from posthog.week_start_day import WeekStartDay
from ..facade import contracts
from ..facade.contracts import HighlightCandidate, HighlightFindings, HighlightSource
-from ..facade.enums import HighlightInterval, HighlightLabel, HighlightPriority, HighlightsStatus
+from ..facade.enums import HighlightInterval, HighlightLabel, HighlightPinStatus, HighlightPriority, HighlightsStatus
from ..feature_flags import pulse_ranking
from ..models import TodayHighlights
from ..temporal.inputs import (
@@ -32,10 +33,13 @@ from ..temporal.inputs import (
FinalizeHighlightsInputs,
HighlightSourceInputs,
HighlightSourceResult,
+ PinnedNumber,
highlights_workflow_id,
)
+from . import pulse_pins
from .highlight_registry import load_sources
from .highlight_types import CACHE_SECONDS, Context, property_restrictions
+from .pinned import PINNED_METRICS
logger = structlog.get_logger(__name__)
@@ -56,15 +60,20 @@ _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()
+ pins = [
+ PinnedNumber(key=pin.key, dashboard_id=pin.dashboard_id)
+ for pin in pulse_pins.get_pins(team=team, user_id=user.id, scopes=scopes)
+ ]
key = _key(team, user, scopes)
+ pins_key = _pins_key(pins)
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)
+ if latest is None or latest.pins_key != pins_key or _is_due(latest, now):
+ _start(team, user, scopes, day, key, pins, pins_key, after=latest.id if latest else None)
status = HighlightsStatus.COMPUTING
else:
status = HighlightsStatus(latest.status)
@@ -87,6 +96,13 @@ def _key(team: Team, user: User, scopes: frozenset[str] | None) -> str:
return hashlib.sha256(f"{granted}:{restrictions}:{pulse_ranking(user, team)}".encode()).hexdigest()[:32]
+def _pins_key(pins: Sequence[PinnedNumber]) -> str:
+ if not pins:
+ return ""
+ signature = ",".join(f"{pin.key}@{pin.dashboard_id or ''}" for pin in pins)
+ return hashlib.sha256(signature.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)
@@ -94,10 +110,22 @@ def _is_due(row: TodayHighlights, now: datetime) -> bool:
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):
+def _start(
+ team: Team,
+ user: User,
+ scopes: frozenset[str] | None,
+ day: date,
+ key: str,
+ pins: list[PinnedNumber],
+ pins_key: str,
+ after: UUID | None,
+) -> None:
+ lock = f"today_highlights:start:{team.id}:{user.id}:{key}:{pins_key}:{day.isoformat()}:{after}"
+ if not cache.add(lock, 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)
+ row = TodayHighlights.objects.for_team(team.id).create(
+ team_id=team.id, user_id=user.id, local_day=day, key=key, pins_key=pins_key
+ )
inputs = ComputeHighlightsInputs(
team_id=team.id,
user_id=user.id,
@@ -105,6 +133,7 @@ def _start(team: Team, user: User, scopes: frozenset[str] | None, day: date, key
local_day=day.isoformat(),
scopes=None if scopes is None else sorted(scopes),
source_names=[source.name for source in load_sources()],
+ pins=pins,
)
try:
asyncio.run(
@@ -128,6 +157,7 @@ def run_source(inputs: HighlightSourceInputs) -> HighlightSourceResult:
User.objects.get(id=inputs.user_id),
date.fromisoformat(inputs.local_day),
None if inputs.scopes is None else frozenset(inputs.scopes),
+ frozenset(inputs.pinned),
)
if source is None or not context.allows(*source.scopes):
return HighlightSourceResult(source_name=inputs.source_name, found=None, failed=False)
@@ -143,7 +173,14 @@ def finalize(inputs: FinalizeHighlightsInputs) -> None:
if row is None:
return
found = {result.source_name: _FINDINGS.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)
+ highlights = build_highlights(
+ load_sources(),
+ found,
+ Team.objects.get(id=inputs.team_id),
+ row.local_day,
+ pins=[pin.key for pin in inputs.pins],
+ pinned={metric.key: metric for metric in PINNED_METRICS.validate_json(inputs.pinned)},
+ )
failed = [result for result in inputs.results if result.failed]
usable = bool(highlights.items or highlights.pulse)
row.status = (
@@ -163,17 +200,24 @@ def finalize(inputs: FinalizeHighlightsInputs) -> None:
def delete_for_teams(team_ids: list[int]) -> None:
TodayHighlights.objects.unscoped().filter(team_id__in=team_ids).delete()
+ pulse_pins.delete_for_teams(team_ids)
def build_highlights(
- sources: Sequence[HighlightSource], found: Mapping[str, HighlightFindings], team: Team, day: date
+ sources: Sequence[HighlightSource],
+ found: Mapping[str, HighlightFindings],
+ team: Team,
+ day: date,
+ pins: Sequence[str] = (),
+ pinned: Mapping[str, contracts.HighlightMetric] | None = None,
) -> 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]
+ offered: dict[str, contracts.HighlightMetric] = {}
+ for source in sorted(sources, key=lambda source: source.pulse_order):
+ for metric in found[source.name].pulse if source.name in found else ():
+ offered.setdefault(metric.key, metric)
+ resolved = {**offered, **(pinned or {})}
+ chosen = [resolved[key] for key in pins if key in resolved]
+ pulse = [*chosen, *(metric for key, metric in offered.items() if key not in pins)][: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,
@@ -185,6 +229,12 @@ def build_highlights(
for metric in pulse
],
items=sorted((_item(c) for c in ranked), key=lambda item: item.priority),
+ pins=[
+ contracts.HighlightPin(
+ key=key, status=HighlightPinStatus.READY if key in resolved else HighlightPinStatus.UNAVAILABLE
+ )
+ for key in pins
+ ],
)
diff --git a/products/today/backend/logic/pinned.py b/products/today/backend/logic/pinned.py
new file mode 100644
index 000000000000..3a8cce00011f
--- /dev/null
+++ b/products/today/backend/logic/pinned.py
@@ -0,0 +1,53 @@
+from dataclasses import replace
+from datetime import date
+from functools import partial
+
+from pydantic import TypeAdapter
+
+from posthog.clickhouse.query_tagging import Feature, Product, tags_context
+from posthog.models import Team, User
+
+from products.customer_analytics.backend.facade.api import get_key_metrics
+
+from ..facade import contracts
+from ..temporal.inputs import PinnedNumber, ResolvePinsInputs, ResolvePinsResult
+from .highlight_sources.key_metrics import tile
+from .highlight_sources.routine import dashboard_tile_metric, insight_metric
+from .highlight_types import Context
+from .pulse_pins import INSIGHT_PREFIX, required_scopes
+
+PINNED_METRICS = TypeAdapter(list[contracts.HighlightMetric])
+
+
+def resolve_pins(inputs: ResolvePinsInputs) -> ResolvePinsResult:
+ 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),
+ )
+ metrics: list[contracts.HighlightMetric] = []
+ with tags_context(product=Product.TODAY, feature=Feature.QUERY, team_id=context.team.id):
+ for pin in inputs.pins:
+ if not pin.key.startswith(INSIGHT_PREFIX) or not context.allows(
+ *required_scopes(pin.key, pin.dashboard_id)
+ ):
+ continue
+ metric = context.guard(f"pinned {pin.key}", partial(_insight, context, pin), None)
+ if metric is not None:
+ metrics.append(replace(metric, reason=None))
+ key_metrics = [pin.key for pin in inputs.pins if not pin.key.startswith(INSIGHT_PREFIX)]
+ if key_metrics and context.allows("customer_analytics:read"):
+ found = context.guard(
+ "pinned key metrics", partial(get_key_metrics, team=context.team, user=context.user), None
+ )
+ by_key = {metric.key: metric for metric in found or []}
+ metrics.extend(replace(tile(by_key[key]), reason=None) for key in key_metrics if key in by_key)
+ return ResolvePinsResult(found=PINNED_METRICS.dump_json(metrics).decode())
+
+
+def _insight(context: Context, pin: PinnedNumber) -> contracts.HighlightMetric | None:
+ short_id = pin.key.removeprefix(INSIGHT_PREFIX)
+ if pin.dashboard_id is not None:
+ return dashboard_tile_metric(context, pin.dashboard_id, short_id, blocking=True)
+ return insight_metric(context, short_id, blocking=True)
diff --git a/products/today/backend/logic/pulse_pins.py b/products/today/backend/logic/pulse_pins.py
new file mode 100644
index 000000000000..869bf337730b
--- /dev/null
+++ b/products/today/backend/logic/pulse_pins.py
@@ -0,0 +1,63 @@
+from django.db import IntegrityError, transaction
+from django.utils import timezone
+
+from pydantic import TypeAdapter, ValidationError
+
+from posthog.models import Team
+from posthog.scopes import scopes_not_covered
+
+from ..facade import contracts
+from ..models import TodayPulsePins
+
+MAX_PULSE_PINS = 4
+INSIGHT_PREFIX = "insight:"
+
+_PINS = TypeAdapter(list[contracts.PulsePin])
+
+
+def required_scopes(key: str, dashboard_id: int | None) -> tuple[str, ...]:
+ if not key.startswith(INSIGHT_PREFIX):
+ return ("customer_analytics:read",)
+ return ("insight:read",) if dashboard_id is None else ("insight:read", "dashboard:read")
+
+
+def get_pins(*, team: Team, user_id: int, scopes: frozenset[str] | None) -> list[contracts.PulsePin]:
+ row = TodayPulsePins.objects.for_team(_canonical(team), canonical=True).filter(user_id=user_id).first()
+ if row is None:
+ return []
+ try:
+ pins = _PINS.validate_python(row.pins)
+ except ValidationError:
+ return []
+ if scopes is None or "*" in scopes:
+ return pins
+ return [pin for pin in pins if not scopes_not_covered(scopes, required_scopes(pin.key, pin.dashboard_id))]
+
+
+def set_pins(*, team: Team, user_id: int, pins: list[contracts.PulsePin]) -> list[contracts.PulsePin]:
+ team_id = _canonical(team)
+ kept: dict[str, contracts.PulsePin] = {}
+ for pin in pins:
+ kept.setdefault(pin.key, pin)
+ if len(kept) == MAX_PULSE_PINS:
+ break
+ kept_pins = list(kept.values())
+ stored = _PINS.dump_python(kept_pins, mode="json")
+ try:
+ with transaction.atomic():
+ TodayPulsePins.objects.for_team(team_id, canonical=True).update_or_create(
+ team_id=team_id, user_id=user_id, defaults={"pins": stored}
+ )
+ except IntegrityError:
+ TodayPulsePins.objects.for_team(team_id, canonical=True).filter(user_id=user_id).update(
+ pins=stored, updated_at=timezone.now()
+ )
+ return kept_pins
+
+
+def _canonical(team: Team) -> int:
+ return team.parent_team_id or team.id
+
+
+def delete_for_teams(team_ids: list[int]) -> None:
+ TodayPulsePins.objects.unscoped().filter(team_id__in=team_ids).delete()
diff --git a/products/today/backend/migrations/0004_todaypulsepins.py b/products/today/backend/migrations/0004_todaypulsepins.py
new file mode 100644
index 000000000000..a3658829ccd7
--- /dev/null
+++ b/products/today/backend/migrations/0004_todaypulsepins.py
@@ -0,0 +1,46 @@
+# Generated by Django 5.2.18 on 2026-10-20 16:25
+
+import django.db.models.manager
+from django.db import migrations, models
+
+import posthog.uuidt
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("today", "0003_delete_dailybriefing"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="TodayPulsePins",
+ 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()),
+ ("pins", models.JSONField(default=list)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ ],
+ options={
+ "abstract": False,
+ "default_manager_name": "all_teams",
+ "constraints": [
+ models.UniqueConstraint(
+ fields=("team_id", "user_id"),
+ name="today_pulse_pins_unique_user",
+ )
+ ],
+ },
+ managers=[
+ ("all_teams", django.db.models.manager.Manager()),
+ ],
+ ),
+ ]
diff --git a/products/today/backend/migrations/0005_todayhighlights_pins_key.py b/products/today/backend/migrations/0005_todayhighlights_pins_key.py
new file mode 100644
index 000000000000..759fa5f6fedb
--- /dev/null
+++ b/products/today/backend/migrations/0005_todayhighlights_pins_key.py
@@ -0,0 +1,17 @@
+# Generated by Django 5.2.18 on 2026-10-21 09:39
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("today", "0004_todaypulsepins"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="todayhighlights",
+ name="pins_key",
+ field=models.CharField(blank=True, db_default="", default="", max_length=32),
+ ),
+ ]
diff --git a/products/today/backend/migrations/max_migration.txt b/products/today/backend/migrations/max_migration.txt
index 6e556de3a0a2..a85de0d50f43 100644
--- a/products/today/backend/migrations/max_migration.txt
+++ b/products/today/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0003_delete_dailybriefing
+0005_todayhighlights_pins_key
diff --git a/products/today/backend/models.py b/products/today/backend/models.py
index bf58793f1906..8f988f9cc286 100644
--- a/products/today/backend/models.py
+++ b/products/today/backend/models.py
@@ -13,6 +13,7 @@ class TodayHighlights(ProductTeamModel):
user_id = models.BigIntegerField()
local_day = models.DateField()
key = models.CharField(max_length=32)
+ pins_key = models.CharField(max_length=32, default="", db_default="", blank=True)
status = models.CharField(max_length=16, choices=HighlightsStatus.choices, default=HighlightsStatus.COMPUTING.value)
content = models.JSONField(default=dict)
failed_sources = models.BooleanField(default=False)
@@ -26,3 +27,18 @@ class TodayHighlights(ProductTeamModel):
def __str__(self) -> str:
return f"{self.user_id} {self.local_day} {self.status}"
+
+
+class TodayPulsePins(ProductTeamModel):
+ id = models.UUIDField(primary_key=True, default=uuid7, editable=False)
+ user_id = models.BigIntegerField()
+ pins = models.JSONField(default=list)
+ updated_at = models.DateTimeField(auto_now=True)
+
+ class Meta(ProductTeamModel.Meta):
+ constraints = [
+ models.UniqueConstraint(fields=["team_id", "user_id"], name="today_pulse_pins_unique_user"),
+ ]
+
+ def __str__(self) -> str:
+ return f"{self.user_id} {len(self.pins)} pins"
diff --git a/products/today/backend/presentation/serializers.py b/products/today/backend/presentation/serializers.py
index efa0a26c9e8f..08ae3007ddfb 100644
--- a/products/today/backend/presentation/serializers.py
+++ b/products/today/backend/presentation/serializers.py
@@ -1,5 +1,7 @@
"""DRF serializers for today. Response shapes come from the facade contracts."""
+from typing import Any
+
from rest_framework import serializers
from rest_framework_dataclasses.serializers import DataclassSerializer
@@ -10,6 +12,7 @@ from ..facade.contracts import (
HighlightItem,
HighlightMetric,
HighlightMover,
+ HighlightPin,
Highlights,
HighlightValueFormat,
ImpactNumber,
@@ -18,6 +21,8 @@ from ..facade.contracts import (
PageLink,
PreviewLine,
PullRequestLink,
+ PulsePin,
+ PulsePins,
RecordingTarget,
ReportKeyClauses,
ReportPage,
@@ -31,6 +36,7 @@ from ..facade.enums import (
HighlightInterval,
HighlightLabel,
HighlightMetricReason,
+ HighlightPinStatus,
HighlightPriority,
HighlightsStatus,
HighlightUnit,
@@ -286,6 +292,43 @@ class HighlightMoverSerializer(DataclassSerializer):
dataclass = HighlightMover
+class PulsePinSerializer(DataclassSerializer):
+ key = serializers.CharField(
+ max_length=200,
+ help_text="Key of the number to keep: a key metric setting such as signup_event, or insight:<short_id>.",
+ )
+ name = serializers.CharField(
+ max_length=400, help_text="Name to show for the number until the highlights compute its value."
+ )
+ dashboard_id = serializers.IntegerField(
+ required=False,
+ allow_null=True,
+ default=None,
+ help_text="For an insight pinned from a dashboard tile, the dashboard whose filters it keeps. Null otherwise.",
+ )
+
+ class Meta:
+ dataclass = PulsePin
+
+
+MAX_PINS_IN_REQUEST = 20
+
+
+class PulsePinsSerializer(DataclassSerializer):
+ pins = PulsePinSerializer(
+ many=True,
+ help_text=f"Numbers the person keeps at the start of the key numbers, in order. Suggestions fill the free places. Only the first 4 distinct keys are kept. At most {MAX_PINS_IN_REQUEST} entries.",
+ )
+
+ class Meta:
+ dataclass = PulsePins
+
+ def to_internal_value(self, data: Any) -> PulsePins:
+ if isinstance(data, dict) and isinstance(data.get("pins"), list) and len(data["pins"]) > MAX_PINS_IN_REQUEST:
+ raise serializers.ValidationError({"pins": [f"Send at most {MAX_PINS_IN_REQUEST} pins."]})
+ return super().to_internal_value(data)
+
+
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>."
@@ -324,12 +367,16 @@ class HighlightMetricSerializer(DataclassSerializer):
reason = serializers.ChoiceField(
choices=HighlightMetricReason.choices,
allow_null=True,
- help_text="Why the pulse shows the metric: `routine` for an insight the person opens often, `dashboard` for a tile of a dashboard they open often, `key_metric` for a key metric of the project. Null for metrics computed before this field existed.",
+ help_text="Why the pulse suggests the metric: `routine` for an insight the person opens often, `dashboard` for a tile of a dashboard they open often, `key_metric` for a key metric of the project. Null for a number the person pinned, which `pins` lists, and for metrics computed before this field existed.",
)
dashboard_name = serializers.CharField(
allow_null=True,
help_text="Name of the dashboard the tile comes from when `reason` is `dashboard`, else null.",
)
+ dashboard_id = serializers.IntegerField(
+ allow_null=True,
+ help_text="Id of the dashboard the tile comes from, with its filters applied. Pass it when pinning the tile. Null otherwise.",
+ )
opened_days = serializers.IntegerField(
allow_null=True,
help_text="On how many of the last 14 days the person opened the insight, or the dashboard of the tile. Null for a key metric.",
@@ -378,6 +425,17 @@ class HighlightItemSerializer(DataclassSerializer):
}
+class HighlightPinSerializer(DataclassSerializer):
+ key = serializers.CharField(help_text="Key of a number the person keeps on their home.")
+ status = serializers.ChoiceField(
+ choices=HighlightPinStatus.choices,
+ help_text="`ready` when the number is in `pulse`. `unavailable` when it has no number to show, for example a deleted insight, one that is not a trend, or a query that failed or did not finish in time. A pin missing from this list was added after these highlights were computed.",
+ )
+
+ class Meta:
+ dataclass = HighlightPin
+
+
class HighlightsSerializer(DataclassSerializer):
status = serializers.ChoiceField(
choices=HighlightsStatus.choices,
@@ -395,6 +453,10 @@ class HighlightsSerializer(DataclassSerializer):
many=True,
help_text="Up to 6 items, the highest scores across sources, in display order: by `priority`, then by `score`, highest first.",
)
+ pins = HighlightPinSerializer(
+ many=True,
+ help_text="The numbers the person keeps, in their order, with the state of each one. Pinned numbers lead `pulse`.",
+ )
class Meta:
dataclass = Highlights
diff --git a/products/today/backend/presentation/views.py b/products/today/backend/presentation/views.py
index 8180a9febb53..c3c603c370b1 100644
--- a/products/today/backend/presentation/views.py
+++ b/products/today/backend/presentation/views.py
@@ -11,7 +11,7 @@ from rest_framework.decorators import action
from rest_framework.exceptions import APIException, NotFound, PermissionDenied
from rest_framework.request import Request
from rest_framework.response import Response
-from rest_framework.throttling import UserRateThrottle
+from rest_framework.throttling import BaseThrottle, UserRateThrottle
from posthog.api.mixins import validated_request
from posthog.api.routing import TeamAndOrgViewSetMixin
@@ -30,6 +30,7 @@ from .serializers import (
FigureMarksSerializer,
HighlightsSerializer,
KeyClausesQuerySerializer,
+ PulsePinsSerializer,
ReportKeyClausesSerializer,
ReportPageSerializer,
)
@@ -57,6 +58,19 @@ class JevSustainedThrottle(UserRateThrottle):
JEV_THROTTLES = [BurstRateThrottle, SustainedRateThrottle, JevBurstThrottle, JevSustainedThrottle]
+class PulsePinsBurstThrottle(UserRateThrottle):
+ scope = "today_pulse_pins_burst"
+ rate = "30/minute"
+
+
+class PulsePinsSustainedThrottle(UserRateThrottle):
+ scope = "today_pulse_pins_sustained"
+ rate = "300/day"
+
+
+PULSE_PIN_THROTTLES = [BurstRateThrottle, SustainedRateThrottle, PulsePinsBurstThrottle, PulsePinsSustainedThrottle]
+
+
@contextmanager
def _jev_errors_as_responses(team_id: int) -> Iterator[None]:
try:
@@ -71,8 +85,13 @@ def _jev_errors_as_responses(team_id: int) -> Iterator[None]:
class TodayViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
scope_object = "today"
- scope_object_read_actions = ["excerpt_choice", "highlights"]
- scope_object_write_actions: list[str] = []
+ scope_object_read_actions = ["excerpt_choice", "highlights", "pulse_pins"]
+ scope_object_write_actions = ["set_pulse_pins"]
+
+ def get_throttles(self) -> list[BaseThrottle]:
+ if self.action == "set_pulse_pins":
+ return [throttle() for throttle in PULSE_PIN_THROTTLES]
+ return super().get_throttles()
def _jev_user(self) -> User:
user = cast(User, self.request.user)
@@ -98,6 +117,34 @@ class TodayViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
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=PulsePinsSerializer)},
+ summary="Get the numbers the person keeps",
+ description="The numbers the person keeps at the start of the key numbers on their home, in order. Suggestions fill the free places. 404 when the person does not have the new navigation.",
+ )
+ @action(detail=False, methods=["get"], url_path="pulse_pins")
+ def pulse_pins(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_pulse_pins(team=self.team, user=user, scopes=None if scopes is None else frozenset(scopes))
+ return Response(PulsePinsSerializer(found).data)
+
+ @validated_request(
+ request_serializer=PulsePinsSerializer,
+ responses={200: OpenApiResponse(response=PulsePinsSerializer)},
+ summary="Set the numbers the person keeps",
+ description="Replaces the numbers the person keeps at the start of the key numbers, in order. Repeated keys are dropped and only the first 4 are kept. The next highlights request computes the new numbers. 404 when the person does not have the new navigation.",
+ )
+ @pulse_pins.mapping.put
+ def set_pulse_pins(self, request: Request, **kwargs) -> Response:
+ user = cast(User, request.user)
+ if not api.is_enabled_for(user, self.team):
+ raise NotFound()
+ saved = api.set_pulse_pins(team=self.team, user=user, pins=request.validated_data.pins)
+ return Response(PulsePinsSerializer(saved).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 433a15c18ad1..60af3d5da772 100644
--- a/products/today/backend/temporal/activities.py
+++ b/products/today/backend/temporal/activities.py
@@ -4,8 +4,14 @@ import temporalio.activity
from posthog.sync import database_sync_to_async
-from ..logic import highlights
-from .inputs import FinalizeHighlightsInputs, HighlightSourceInputs, HighlightSourceResult
+from ..logic import highlights, pinned
+from .inputs import (
+ FinalizeHighlightsInputs,
+ HighlightSourceInputs,
+ HighlightSourceResult,
+ ResolvePinsInputs,
+ ResolvePinsResult,
+)
@temporalio.activity.defn
@@ -13,6 +19,11 @@ async def run_highlight_source_activity(inputs: HighlightSourceInputs) -> Highli
return await database_sync_to_async(highlights.run_source, thread_sensitive=False)(inputs)
+async def resolve_pins_activity(inputs: ResolvePinsInputs) -> ResolvePinsResult:
+ return await database_sync_to_async(pinned.resolve_pins, thread_sensitive=False)(inputs)
+
+
@temporalio.activity.defn
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 7ccc0b1d323b..d2dfce46290b 100644
--- a/products/today/backend/temporal/inputs.py
+++ b/products/today/backend/temporal/inputs.py
@@ -5,6 +5,12 @@ import dataclasses
HIGHLIGHTS_WORKFLOW_NAME = "today-compute-highlights"
[email protected](frozen=True)
+class PinnedNumber:
+ key: str
+ dashboard_id: int | None = None
+
+
@dataclasses.dataclass(frozen=True)
class ComputeHighlightsInputs:
team_id: int
@@ -13,6 +19,7 @@ class ComputeHighlightsInputs:
local_day: str
scopes: list[str] | None
source_names: list[str]
+ pins: list[PinnedNumber] = dataclasses.field(default_factory=list)
@dataclasses.dataclass(frozen=True)
@@ -22,6 +29,7 @@ class HighlightSourceInputs:
local_day: str
scopes: list[str] | None
source_name: str
+ pinned: list[str] = dataclasses.field(default_factory=list)
@dataclasses.dataclass(frozen=True)
@@ -31,11 +39,27 @@ class HighlightSourceResult:
failed: bool
[email protected](frozen=True)
+class ResolvePinsInputs:
+ team_id: int
+ user_id: int
+ local_day: str
+ scopes: list[str] | None
+ pins: list[PinnedNumber]
+
+
[email protected](frozen=True)
+class ResolvePinsResult:
+ found: str
+
+
@dataclasses.dataclass(frozen=True)
class FinalizeHighlightsInputs:
team_id: int
highlights_id: str
results: list[HighlightSourceResult]
+ pins: list[PinnedNumber] = dataclasses.field(default_factory=list)
+ pinned: str = "[]"
def highlights_workflow_id(team_id: int, user_id: int, highlights_id: str) -> str:
diff --git a/products/today/backend/temporal/workflows.py b/products/today/backend/temporal/workflows.py
index 6c368c9ce16b..6257c82e2698 100644
--- a/products/today/backend/temporal/workflows.py
+++ b/products/today/backend/temporal/workflows.py
@@ -10,17 +10,19 @@ from temporalio.exceptions import ActivityError
from posthog.temporal.common.base import PostHogWorkflow
with temporalio.workflow.unsafe.imports_passed_through():
- from .activities import finalize_highlights_activity, run_highlight_source_activity
+ from .activities import finalize_highlights_activity, resolve_pins_activity, run_highlight_source_activity
from .inputs import (
HIGHLIGHTS_WORKFLOW_NAME,
ComputeHighlightsInputs,
FinalizeHighlightsInputs,
HighlightSourceInputs,
HighlightSourceResult,
+ ResolvePinsInputs,
)
HIGHLIGHT_SOURCE_TIMEOUT = timedelta(seconds=60)
FINALIZE_HIGHLIGHTS_TIMEOUT = timedelta(seconds=30)
+PINNED_NUMBERS_PATCH = "today-pinned-numbers"
@temporalio.workflow.defn(name=HIGHLIGHTS_WORKFLOW_NAME)
@@ -29,10 +31,20 @@ class ComputeTodayHighlightsWorkflow(PostHogWorkflow):
@temporalio.workflow.run
async def run(self, inputs: ComputeHighlightsInputs) -> None:
- results = await asyncio.gather(*(_run_source(inputs, name) for name in inputs.source_names))
+ sources = asyncio.gather(*(_run_source(inputs, name) for name in inputs.source_names))
+ if temporalio.workflow.patched(PINNED_NUMBERS_PATCH) and inputs.pins:
+ results, pinned = await asyncio.gather(sources, _resolve_pins(inputs))
+ else:
+ results, pinned = await sources, "[]"
await temporalio.workflow.execute_activity(
finalize_highlights_activity,
- FinalizeHighlightsInputs(team_id=inputs.team_id, highlights_id=inputs.highlights_id, results=list(results)),
+ FinalizeHighlightsInputs(
+ team_id=inputs.team_id,
+ highlights_id=inputs.highlights_id,
+ results=list(results),
+ pins=inputs.pins,
+ pinned=pinned,
+ ),
start_to_close_timeout=FINALIZE_HIGHLIGHTS_TIMEOUT,
retry_policy=temporalio.common.RetryPolicy(maximum_attempts=3),
)
@@ -48,9 +60,29 @@ async def _run_source(inputs: ComputeHighlightsInputs, source_name: str) -> High
local_day=inputs.local_day,
scopes=inputs.scopes,
source_name=source_name,
+ pinned=[pin.key for pin in inputs.pins],
),
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)
+
+
+async def _resolve_pins(inputs: ComputeHighlightsInputs) -> str:
+ try:
+ result = await temporalio.workflow.execute_activity(
+ resolve_pins_activity,
+ ResolvePinsInputs(
+ team_id=inputs.team_id,
+ user_id=inputs.user_id,
+ local_day=inputs.local_day,
+ scopes=inputs.scopes,
+ pins=inputs.pins,
+ ),
+ start_to_close_timeout=HIGHLIGHT_SOURCE_TIMEOUT,
+ retry_policy=temporalio.common.RetryPolicy(maximum_attempts=1),
+ )
+ except ActivityError:
+ return "[]"
+ return result.found
diff --git a/products/today/backend/tests/test_api.py b/products/today/backend/tests/test_api.py
index 98b766272589..602b320ef11d 100644
--- a/products/today/backend/tests/test_api.py
+++ b/products/today/backend/tests/test_api.py
@@ -1,6 +1,6 @@
import json
from dataclasses import replace
-from datetime import UTC, datetime
+from datetime import UTC, datetime, timedelta
from typing import TYPE_CHECKING
import time_machine
@@ -27,13 +27,14 @@ from posthog.models.personal_api_key import hash_key_value
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.logic import highlights
+from products.today.backend.logic import highlights, pinned
from products.today.backend.logic.highlight_types import Found, Source
from products.today.backend.logic.jev import JevPick
from products.today.backend.temporal.inputs import (
ComputeHighlightsInputs,
FinalizeHighlightsInputs,
HighlightSourceInputs,
+ ResolvePinsInputs,
)
from products.today.backend.tests.conftest import TodayTeamScopedTestMixin
from products.today.backend.tests.factories import AGREEING, FakeJev, SameAnswerJev, page_source
@@ -273,6 +274,9 @@ class TestTodayAPI(TodayTeamScopedTestMixin, APIBaseTest):
status.HTTP_403_FORBIDDEN,
),
("highlights with only today", "get", "highlights", ["today:read"], status.HTTP_403_FORBIDDEN),
+ ("pins with today read", "get", "pulse_pins", ["today:read"], status.HTTP_200_OK),
+ ("saving pins with today read", "put", "pulse_pins", ["today:read"], status.HTTP_403_FORBIDDEN),
+ ("saving pins with today write", "put", "pulse_pins", ["today:write"], status.HTTP_200_OK),
]
)
def test_a_scoped_key_reads_data_only_with_its_underlying_scope(
@@ -289,6 +293,8 @@ class TestTodayAPI(TodayTeamScopedTestMixin, APIBaseTest):
):
response = getattr(self.client, method)(
f"/api/projects/{self.team.id}/today/{path}/",
+ {"pins": []} if method == "put" else None,
+ format="json",
HTTP_AUTHORIZATION=f"Bearer {raw_key}",
)
@@ -348,14 +354,18 @@ def _temporal() -> MagicMock:
class TestTodayHighlightsAPI(TodayTeamScopedTestMixin, APIBaseTest):
- def _get(self, connect: MagicMock, flag: bool = True) -> "_MonkeyPatchedResponse":
+ def _get(self, connect: MagicMock, flag: bool = True, pulse: tuple[str, ...] = ("k1",)) -> "_MonkeyPatchedResponse":
source = Source(
- name="alerts", find=lambda _c: Found(items=(candidate("alert:1", "alerts", 0.8),), pulse=(metric("k1"),))
+ name="alerts",
+ find=lambda _c: Found(
+ items=(candidate("alert:1", "alerts", 0.8),), pulse=tuple(metric(key) for key in pulse)
+ ),
)
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),
+ patch.object(pinned, "get_key_metrics", return_value=[]),
):
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:
@@ -372,9 +382,26 @@ class TestTodayHighlightsAPI(TodayTeamScopedTestMixin, APIBaseTest):
)
for name in inputs.source_names
]
+ found_pins = (
+ pinned.resolve_pins(
+ ResolvePinsInputs(
+ team_id=inputs.team_id,
+ user_id=inputs.user_id,
+ local_day=inputs.local_day,
+ scopes=inputs.scopes,
+ pins=inputs.pins,
+ )
+ ).found
+ if inputs.pins
+ else "[]"
+ )
highlights.finalize(
FinalizeHighlightsInputs(
- team_id=inputs.team_id, highlights_id=inputs.highlights_id, results=results
+ team_id=inputs.team_id,
+ highlights_id=inputs.highlights_id,
+ results=results,
+ pins=inputs.pins,
+ pinned=found_pins,
)
)
return response
@@ -413,3 +440,49 @@ class TestTodayHighlightsAPI(TodayTeamScopedTestMixin, APIBaseTest):
False,
),
)
+
+ def test_pinned_numbers_lead_the_pulse_and_a_new_pin_starts_a_new_computation(self) -> None:
+ cache.clear()
+ with time_machine.travel(datetime(2026, 10, 13, 12, 0, tzinfo=UTC), tick=False) as clock:
+ self._get(_temporal(), pulse=("k1", "k2"))
+ pins = [{"key": key, "name": key} for key in ("k2", "k2", "a", "b", "c", "d")]
+ clock.shift(timedelta(seconds=1))
+ with patch("products.today.backend.feature_flags.feature_enabled_or_false", return_value=True):
+ saved = self.client.put(
+ f"/api/projects/{self.team.id}/today/pulse_pins/", {"pins": pins}, format="json"
+ )
+ read = self.client.get(f"/api/projects/{self.team.id}/today/pulse_pins/")
+ connect = _temporal()
+ during = self._get(connect, pulse=("k1", "k2")).json()
+ after = self._get(_temporal(), pulse=("k1", "k2")).json()
+ with patch("products.today.backend.feature_flags.feature_enabled_or_false", return_value=True):
+ self.client.put(f"/api/projects/{self.team.id}/today/pulse_pins/", {"pins": []}, format="json")
+ back = _temporal()
+ self._get(back, pulse=("k1", "k2"))
+
+ self.assertEqual(
+ (
+ [pin["key"] for pin in saved.json()["pins"]],
+ read.json() == saved.json(),
+ (connect.return_value.start_workflow.called, back.return_value.start_workflow.called),
+ (during["status"], [m["key"] for m in during["pulse"]]),
+ [m["key"] for m in after["pulse"]],
+ [(pin["key"], pin["status"]) for pin in after["pins"]],
+ ),
+ (
+ ["k2", "a", "b", "c"],
+ True,
+ (True, True),
+ ("computing", ["k1", "k2"]),
+ ["k2", "k1"],
+ [("k2", "ready"), ("a", "unavailable"), ("b", "unavailable"), ("c", "unavailable")],
+ ),
+ )
+
+ def test_saving_too_many_pins_is_rejected(self) -> None:
+ pins = [{"key": f"k{index}", "name": f"k{index}"} for index in range(21)]
+
+ with patch("products.today.backend.feature_flags.feature_enabled_or_false", return_value=True):
+ response = self.client.put(f"/api/projects/{self.team.id}/today/pulse_pins/", {"pins": pins}, format="json")
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
diff --git a/products/today/backend/tests/test_highlight_insights.py b/products/today/backend/tests/test_highlight_insights.py
index c12ec9e54251..bebf82e89ff6 100644
--- a/products/today/backend/tests/test_highlight_insights.py
+++ b/products/today/backend/tests/test_highlight_insights.py
@@ -400,3 +400,31 @@ class TestRoutineInsights(BaseTest):
pulse = routine.find(Context(self.team, self.user, TODAY)).pulse
self.assertEqual([m.key for m in pulse], expected)
+
+ @time_machine.travel("2026-10-13T12:00:00Z", tick=False)
+ def test_suggestions_skip_pinned_insights_and_leave_their_places_free(self) -> None:
+ for ref in ("pinned", "first", "second", "third"):
+ FileSystemViewLog.objects.create(
+ team=self.team,
+ user=self.user,
+ type="insight",
+ ref=ref,
+ view_days=[TODAY - timedelta(days=1)],
+ viewed_at=datetime.combine(TODAY - timedelta(days=1), time(12), tzinfo=UTC),
+ )
+ points = [(TODAY - timedelta(days=d), 2.0 if d <= 7 else 1.0) for d in range(14, 0, -1)]
+ queried: list[str] = []
+
+ def series(**kwargs: Any) -> InsightSeries:
+ queried.append(kwargs["short_id"])
+ return insight({"opened": points}, short_id=kwargs["short_id"], name=kwargs["short_id"])
+
+ with (
+ patch.object(routine, "pulse_ranking", return_value="frecency"),
+ patch.object(routine, "get_insight_series", side_effect=series),
+ ):
+ pulse = routine.find(
+ Context(self.team, self.user, TODAY, pinned=frozenset({"insight:pinned", "signup_event"}))
+ ).pulse
+
+ self.assertEqual((len(pulse), "pinned" in queried), (2, False))
diff --git a/products/today/backend/tests/test_highlights.py b/products/today/backend/tests/test_highlights.py
index 0b6904b30fc3..89587a653433 100644
--- a/products/today/backend/tests/test_highlights.py
+++ b/products/today/backend/tests/test_highlights.py
@@ -168,6 +168,31 @@ class TestBuildHighlights(SimpleTestCase):
),
)
+ def test_pins_lead_the_pulse_and_each_pin_reports_its_state(self) -> None:
+ source = HighlightSource(name="metrics", find=lambda _c: HighlightFindings())
+
+ built = highlights.build_highlights(
+ (source,),
+ {"metrics": HighlightFindings(pulse=(metric("offered"), metric("suggested")))},
+ Team(timezone="UTC"),
+ DAY,
+ pins=["insight:pinned", "offered", "insight:slow", "insight:gone"],
+ pinned={"insight:pinned": metric("insight:pinned")},
+ )
+
+ self.assertEqual(
+ ([m.key for m in built.pulse], [(pin.key, pin.status) for pin in built.pins]),
+ (
+ ["insight:pinned", "offered", "suggested"],
+ [
+ ("insight:pinned", "ready"),
+ ("offered", "ready"),
+ ("insight:slow", "unavailable"),
+ ("insight:gone", "unavailable"),
+ ],
+ ),
+ )
+
@parameterized.expand(
[
("days", HighlightInterval.DAY, None, 3, [date(2026, 10, 10), date(2026, 10, 11), date(2026, 10, 12)]),
diff --git a/products/today/backend/tests/test_pinned.py b/products/today/backend/tests/test_pinned.py
new file mode 100644
index 000000000000..2909bbd7d01c
--- /dev/null
+++ b/products/today/backend/tests/test_pinned.py
@@ -0,0 +1,174 @@
+from datetime import date, timedelta
+from typing import Any
+
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from parameterized import parameterized
+from pydantic import TypeAdapter
+
+from posthog.models import Team
+
+from products.customer_analytics.backend.facade.contracts import KeyMetric
+from products.dashboards.backend.facade.api import DashboardInsights, DashboardInsightTile
+from products.product_analytics.backend.facade.contracts import InsightSeries
+from products.today.backend.facade import contracts
+from products.today.backend.facade.contracts import PulsePin
+from products.today.backend.logic import pinned, pulse_pins
+from products.today.backend.logic.highlight_sources import routine
+from products.today.backend.temporal.inputs import PinnedNumber, ResolvePinsInputs
+
+TODAY = date(2026, 10, 13)
+METRICS = TypeAdapter(list[contracts.HighlightMetric])
+POINTS = [(TODAY - timedelta(days=d), 2.0 if d <= 7 else 1.0) for d in range(14, 0, -1)]
+
+
+def key_metric(key: str, this_week: float, last_week: float) -> KeyMetric:
+ return KeyMetric(
+ key=key,
+ name=key,
+ people=False,
+ daily=[(day, 0.0) for day, _ in POINTS],
+ this_week=this_week,
+ last_week=last_week,
+ node={"kind": "EventsNode", "event": key},
+ )
+
+
+class TestPinnedNumbers(BaseTest):
+ def test_saving_pins_twice_in_a_child_environment_updates_the_one_row(self) -> None:
+ child = Team.objects.create(
+ organization=self.organization, project=self.team.project, parent_team=self.team, name="Child"
+ )
+
+ for key in ("insight:first", "insight:second"):
+ pulse_pins.set_pins(team=child, user_id=self.user.id, pins=[PulsePin(key=key, name=key)])
+
+ self.assertEqual(
+ [pin.key for pin in pulse_pins.get_pins(team=child, user_id=self.user.id, scopes=None)], ["insight:second"]
+ )
+
+ @parameterized.expand(
+ [
+ ("a session", None, ["insight:a", "insight:b", "revenue"]),
+ ("a key with only today", ["today:read"], []),
+ ("a key with insights", ["today:read", "insight:read"], ["insight:a"]),
+ (
+ "a key with insights and dashboards",
+ ["today:read", "insight:read", "dashboard:read"],
+ ["insight:a", "insight:b"],
+ ),
+ ("a key with key metrics", ["today:read", "customer_analytics:read"], ["revenue"]),
+ ]
+ )
+ def test_reading_pins_returns_only_the_ones_the_scopes_cover(
+ self, _name: str, scopes: list[str] | None, expected: list[str]
+ ) -> None:
+ pulse_pins.set_pins(
+ team=self.team,
+ user_id=self.user.id,
+ pins=[
+ PulsePin("insight:a", "A"),
+ PulsePin("insight:b", "B", dashboard_id=7),
+ PulsePin("revenue", "Revenue"),
+ ],
+ )
+
+ found = pulse_pins.get_pins(
+ team=self.team, user_id=self.user.id, scopes=None if scopes is None else frozenset(scopes)
+ )
+
+ self.assertEqual([pin.key for pin in found], expected)
+
+ @parameterized.expand(
+ [
+ ("a cached insight", [PinnedNumber("insight:ready")], None, [], [("insight:ready", None)]),
+ ("an insight with no cached result", [PinnedNumber("insight:cold")], None, [], [("insight:cold", None)]),
+ ("an insight whose query fails", [PinnedNumber("insight:broken")], None, [], []),
+ (
+ "a tile pinned from a dashboard",
+ [PinnedNumber("insight:ready", dashboard_id=7)],
+ None,
+ [],
+ [("insight:ready", "/dashboard/7")],
+ ),
+ ("a tile removed from its dashboard", [PinnedNumber("insight:ready", dashboard_id=8)], None, [], []),
+ (
+ "a key metric with no events in either week",
+ [PinnedNumber("quiet")],
+ None,
+ [key_metric("quiet", 0, 0)],
+ [("quiet", None)],
+ ),
+ ("key metrics still being calculated", [PinnedNumber("quiet")], None, None, []),
+ ("key metrics that fail to load", [PinnedNumber("quiet")], None, ValueError("down"), []),
+ ("a key without insight access", [PinnedNumber("insight:ready")], ["customer_analytics:read"], [], []),
+ (
+ "a dashboard tile without dashboard access",
+ [PinnedNumber("insight:ready", dashboard_id=7)],
+ ["insight:read"],
+ [],
+ [],
+ ),
+ ]
+ )
+ def test_each_pin_is_resolved_on_its_own(
+ self,
+ _name: str,
+ pins: list[PinnedNumber],
+ scopes: list[str] | None,
+ key_metrics: list[KeyMetric] | Exception | None,
+ resolved: list[tuple[str, str | None]],
+ ) -> None:
+ def series(**kwargs: Any) -> InsightSeries | None:
+ if kwargs["short_id"] == "cold" and not kwargs.get("blocking"):
+ return None
+ if kwargs["short_id"] == "broken":
+ raise ValueError("query failed")
+ return InsightSeries(
+ short_id=kwargs["short_id"],
+ name=kwargs["short_id"],
+ series={"opened": POINTS},
+ period="day",
+ averaged_series=[],
+ event_name="",
+ )
+
+ growth = DashboardInsights(
+ dashboard_id=7,
+ name="Growth",
+ filters={},
+ variables=None,
+ tiles=(DashboardInsightTile(insight_short_id="ready", filters_overrides=None),),
+ )
+
+ def tile(**kwargs: Any) -> DashboardInsights | None:
+ return growth if kwargs["dashboard_id"] == 7 else None
+
+ with (
+ patch.object(routine, "get_insight_series", side_effect=series),
+ patch.object(routine, "dashboard_insight_tile", side_effect=tile),
+ patch.object(
+ pinned,
+ "get_key_metrics",
+ side_effect=key_metrics if isinstance(key_metrics, Exception) else None,
+ return_value=None if isinstance(key_metrics, Exception) else key_metrics,
+ ),
+ ):
+ result = pinned.resolve_pins(
+ ResolvePinsInputs(
+ team_id=self.team.id,
+ user_id=self.user.id,
+ local_day=TODAY.isoformat(),
+ scopes=scopes,
+ pins=pins,
+ )
+ )
+
+ self.assertEqual(
+ [
+ (metric.key, metric.url if metric.dashboard_id else None)
+ for metric in METRICS.validate_json(result.found)
+ ],
+ resolved,
+ )
diff --git a/products/today/backend/tests/test_workflows.py b/products/today/backend/tests/test_workflows.py
index 237883e96365..53ca8dc3cb39 100644
--- a/products/today/backend/tests/test_workflows.py
+++ b/products/today/backend/tests/test_workflows.py
@@ -17,6 +17,9 @@ from products.today.backend.temporal.inputs import (
FinalizeHighlightsInputs,
HighlightSourceInputs,
HighlightSourceResult,
+ PinnedNumber,
+ ResolvePinsInputs,
+ ResolvePinsResult,
)
from products.today.backend.temporal.workflows import ComputeTodayHighlightsWorkflow
@@ -27,11 +30,23 @@ async def environment() -> AsyncIterator[WorkflowEnvironment]:
yield env
+PINS = [PinnedNumber("insight:a"), PinnedNumber("insight:b", dashboard_id=7)]
+
+
@pytest.mark.asyncio
-async def test_a_source_that_keeps_failing_is_finalized_as_failed_with_the_others(
- environment: WorkflowEnvironment,
+ "pins,pins_fail,asked,pinned",
+ [
+ ([], False, [], "[]"),
+ (PINS, False, [["insight:a", "insight:b"]], "found"),
+ (PINS, True, [["insight:a", "insight:b"]], "[]"),
+ ],
+)
+async def test_sources_and_pins_are_resolved_once_and_finalized_together(
+ environment: WorkflowEnvironment, pins: list[PinnedNumber], pins_fail: bool, asked: list[list[str]], pinned: str
) -> None:
finalized: list[FinalizeHighlightsInputs] = []
+ resolved: list[list[str]] = []
@activity.defn(name="run_highlight_source_activity")
async def run_source(inputs: HighlightSourceInputs) -> HighlightSourceResult:
@@ -39,6 +54,13 @@ async def test_a_source_that_keeps_failing_is_finalized_as_failed_with_the_other
raise ApplicationError("The source query failed.")
return HighlightSourceResult(source_name=inputs.source_name, found="{}", failed=False)
+ @activity.defn(name="resolve_pins_activity")
+ async def resolve_pins(inputs: ResolvePinsInputs) -> ResolvePinsResult:
+ resolved.append([pin.key for pin in inputs.pins])
+ if pins_fail:
+ raise ApplicationError("The pinned query failed.")
+ return ResolvePinsResult(found="found")
+
@activity.defn(name="finalize_highlights_activity")
async def finalize(inputs: FinalizeHighlightsInputs) -> None:
finalized.append(inputs)
@@ -47,7 +69,7 @@ async def test_a_source_that_keeps_failing_is_finalized_as_failed_with_the_other
environment.client,
task_queue=settings.GENERAL_PURPOSE_TASK_QUEUE,
workflows=[ComputeTodayHighlightsWorkflow],
- activities=[run_source, finalize],
+ activities=[run_source, resolve_pins, finalize],
workflow_runner=UnsandboxedWorkflowRunner(),
):
await environment.client.execute_workflow(
@@ -59,14 +81,22 @@ async def test_a_source_that_keeps_failing_is_finalized_as_failed_with_the_other
local_day="2026-10-13",
scopes=None,
source_names=["alerts", "broken"],
+ pins=pins,
),
id=str(uuid.uuid4()),
task_queue=settings.GENERAL_PURPOSE_TASK_QUEUE,
)
- assert [inputs.results for inputs in finalized] == [
+ assert (resolved, [(inputs.results, inputs.pins, inputs.pinned) for inputs in finalized]) == (
+ asked,
[
- HighlightSourceResult(source_name="alerts", found="{}", failed=False),
- HighlightSourceResult(source_name="broken", found=None, failed=True),
- ]
- ]
+ (
+ [
+ HighlightSourceResult(source_name="alerts", found="{}", failed=False),
+ HighlightSourceResult(source_name="broken", found=None, failed=True),
+ ],
+ pins,
+ pinned,
+ )
+ ],
+ )
diff --git a/products/today/frontend/generated/api.schemas.ts b/products/today/frontend/generated/api.schemas.ts
index c45dda59877a..859cbdc0e6fe 100644
--- a/products/today/frontend/generated/api.schemas.ts
+++ b/products/today/frontend/generated/api.schemas.ts
@@ -153,7 +153,7 @@ export interface HighlightMetricApi {
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[]
- /** Why the pulse shows the metric: `routine` for an insight the person opens often, `dashboard` for a tile of a dashboard they open often, `key_metric` for a key metric of the project. Null for metrics computed before this field existed.
+ /** Why the pulse suggests the metric: `routine` for an insight the person opens often, `dashboard` for a tile of a dashboard they open often, `key_metric` for a key metric of the project. Null for a number the person pinned, which `pins` lists, and for metrics computed before this field existed.
*
* * `routine` - You open this often
* * `dashboard` - On a dashboard you open often
@@ -164,6 +164,11 @@ export interface HighlightMetricApi {
* @nullable
*/
dashboard_name: string | null
+ /**
+ * Id of the dashboard the tile comes from, with its filters applied. Pass it when pinning the tile. Null otherwise.
+ * @nullable
+ */
+ dashboard_id: number | null
/**
* On how many of the last 14 days the person opened the insight, or the dashboard of the tile. Null for a key metric.
* @nullable
@@ -244,6 +249,27 @@ export interface HighlightItemApi {
source: string
}
+/**
+ * * `ready` - Ready
+ * * `unavailable` - Unavailable
+ */
+export type HighlightPinStatusEnumApi = (typeof HighlightPinStatusEnumApi)[keyof typeof HighlightPinStatusEnumApi]
+
+export const HighlightPinStatusEnumApi = {
+ Ready: 'ready',
+ Unavailable: 'unavailable',
+} as const
+
+export interface HighlightPinApi {
+ /** Key of a number the person keeps on their home. */
+ key: string
+ /** `ready` when the number is in `pulse`. `unavailable` when it has no number to show, for example a deleted insight, one that is not a trend, or a query that failed or did not finish in time. A pin missing from this list was added after these highlights were computed.
+ *
+ * * `ready` - Ready
+ * * `unavailable` - Unavailable */
+ status: HighlightPinStatusEnumApi
+}
+
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.
*
@@ -264,6 +290,31 @@ export interface HighlightsApi {
pulse: HighlightMetricApi[]
/** Up to 6 items, the highest scores across sources, in display order: by `priority`, then by `score`, highest first. */
items: HighlightItemApi[]
+ /** The numbers the person keeps, in their order, with the state of each one. Pinned numbers lead `pulse`. */
+ pins: HighlightPinApi[]
+}
+
+export interface PulsePinApi {
+ /**
+ * Key of the number to keep: a key metric setting such as signup_event, or insight:<short_id>.
+ * @maxLength 200
+ */
+ key: string
+ /**
+ * Name to show for the number until the highlights compute its value.
+ * @maxLength 400
+ */
+ name: string
+ /**
+ * For an insight pinned from a dashboard tile, the dashboard whose filters it keeps. Null otherwise.
+ * @nullable
+ */
+ dashboard_id?: number | null
+}
+
+export interface PulsePinsApi {
+ /** Numbers the person keeps at the start of the key numbers, in order. Suggestions fill the free places. Only the first 4 distinct keys are kept. At most 20 entries. */
+ pins: PulsePinApi[]
}
/**
diff --git a/products/today/frontend/generated/api.ts b/products/today/frontend/generated/api.ts
index d89ee646b3e8..50cf87c02150 100644
--- a/products/today/frontend/generated/api.ts
+++ b/products/today/frontend/generated/api.ts
@@ -13,6 +13,7 @@ import type {
ExcerptChoiceRequestApi,
FigureMarksApi,
HighlightsApi,
+ PulsePinsApi,
ReportKeyClausesApi,
ReportPageApi,
TodayReportsKeyClausesRetrieveParams,
@@ -54,6 +55,42 @@ export const todayHighlightsRetrieve = async (projectId: string, options?: Reque
})
}
+export const getTodayPulsePinsRetrieveUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/today/pulse_pins/`
+}
+
+/**
+ * The numbers the person keeps at the start of the key numbers on their home, in order. Suggestions fill the free places. 404 when the person does not have the new navigation.
+ * @summary Get the numbers the person keeps
+ */
+export const todayPulsePinsRetrieve = async (projectId: string, options?: RequestInit): Promise<PulsePinsApi> => {
+ return apiMutator<PulsePinsApi>(getTodayPulsePinsRetrieveUrl(projectId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getTodayPulsePinsUpdateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/today/pulse_pins/`
+}
+
+/**
+ * Replaces the numbers the person keeps at the start of the key numbers, in order. Repeated keys are dropped and only the first 4 are kept. The next highlights request computes the new numbers. 404 when the person does not have the new navigation.
+ * @summary Set the numbers the person keeps
+ */
+export const todayPulsePinsUpdate = async (
+ projectId: string,
+ pulsePinsApi: PulsePinsApi,
+ options?: RequestInit
+): Promise<PulsePinsApi> => {
+ return apiMutator<PulsePinsApi>(getTodayPulsePinsUpdateUrl(projectId), {
+ ...options,
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(pulsePinsApi),
+ })
+}
+
export const getTodayReportsFigureMarksRetrieveUrl = (projectId: string, reportId: string) => {
return `/api/projects/${projectId}/today/reports/${reportId}/figure_marks/`
}
diff --git a/products/today/frontend/generated/api.zod.ts b/products/today/frontend/generated/api.zod.ts
index 68d003731d7f..c52050b3fe4b 100644
--- a/products/today/frontend/generated/api.zod.ts
+++ b/products/today/frontend/generated/api.zod.ts
@@ -31,3 +31,38 @@ export const TodayExcerptChoiceCreateBody = /* @__PURE__ */ zod.object({
.max(todayExcerptChoiceCreateBodyExcerptsMax)
.describe('Candidate code excerpts, best scored first.'),
})
+
+/**
+ * Replaces the numbers the person keeps at the start of the key numbers, in order. Repeated keys are dropped and only the first 4 are kept. The next highlights request computes the new numbers. 404 when the person does not have the new navigation.
+ * @summary Set the numbers the person keeps
+ */
+export const todayPulsePinsUpdateBodyPinsItemKeyMax = 200
+
+export const todayPulsePinsUpdateBodyPinsItemNameMax = 400
+
+export const TodayPulsePinsUpdateBody = /* @__PURE__ */ zod.object({
+ pins: zod
+ .array(
+ zod.object({
+ key: zod
+ .string()
+ .max(todayPulsePinsUpdateBodyPinsItemKeyMax)
+ .describe(
+ 'Key of the number to keep: a key metric setting such as signup_event, or insight:<short_id>.'
+ ),
+ name: zod
+ .string()
+ .max(todayPulsePinsUpdateBodyPinsItemNameMax)
+ .describe('Name to show for the number until the highlights compute its value.'),
+ dashboard_id: zod
+ .number()
+ .nullish()
+ .describe(
+ 'For an insight pinned from a dashboard tile, the dashboard whose filters it keeps. Null otherwise.'
+ ),
+ })
+ )
+ .describe(
+ 'Numbers the person keeps at the start of the key numbers, in order. Suggestions fill the free places. Only the first 4 distinct keys are kept. At most 20 entries.'
+ ),
+})
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 6564ba344d06..e688b29e978d 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -55800,7 +55800,7 @@ export namespace Schemas {
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[];
- /** Why the pulse shows the metric: `routine` for an insight the person opens often, `dashboard` for a tile of a dashboard they open often, `key_metric` for a key metric of the project. Null for metrics computed before this field existed.
+ /** Why the pulse suggests the metric: `routine` for an insight the person opens often, `dashboard` for a tile of a dashboard they open often, `key_metric` for a key metric of the project. Null for a number the person pinned, which `pins` lists, and for metrics computed before this field existed.
*
* * `routine` - You open this often
* * `dashboard` - On a dashboard you open often
@@ -55811,6 +55811,11 @@ export namespace Schemas {
* @nullable
*/
dashboard_name: string | null;
+ /**
+ * Id of the dashboard the tile comes from, with its filters applied. Pass it when pinning the tile. Null otherwise.
+ * @nullable
+ */
+ dashboard_id: number | null;
/**
* On how many of the last 14 days the person opened the insight, or the dashboard of the tile. Null for a key metric.
* @nullable
@@ -55830,6 +55835,28 @@ export namespace Schemas {
movers: HighlightMover[];
}
+ /**
+ * * `ready` - Ready
+ * * `unavailable` - Unavailable
+ */
+ export type HighlightPinStatusEnum = typeof HighlightPinStatusEnum[keyof typeof HighlightPinStatusEnum];
+
+
+ export const HighlightPinStatusEnum = {
+ Ready: 'ready',
+ Unavailable: 'unavailable',
+ } as const;
+
+ export interface HighlightPin {
+ /** Key of a number the person keeps on their home. */
+ key: string;
+ /** `ready` when the number is in `pulse`. `unavailable` when it has no number to show, for example a deleted insight, one that is not a trend, or a query that failed or did not finish in time. A pin missing from this list was added after these highlights were computed.
+ *
+ * * `ready` - Ready
+ * * `unavailable` - Unavailable */
+ status: HighlightPinStatusEnum;
+ }
+
/**
* * `computing` - Computing
* * `ready` - Ready
@@ -55864,6 +55891,8 @@ export namespace Schemas {
pulse: HighlightMetric[];
/** Up to 6 items, the highest scores across sources, in display order: by `priority`, then by `score`, highest first. */
items: HighlightItem[];
+ /** The numbers the person keeps, in their order, with the state of each one. Pinned numbers lead `pulse`. */
+ pins: HighlightPin[];
}
/**
@@ -93657,6 +93686,29 @@ export namespace Schemas {
limit: number;
}
+ export interface PulsePin {
+ /**
+ * Key of the number to keep: a key metric setting such as signup_event, or insight:<short_id>.
+ * @maxLength 200
+ */
+ key: string;
+ /**
+ * Name to show for the number until the highlights compute its value.
+ * @maxLength 400
+ */
+ name: string;
+ /**
+ * For an insight pinned from a dashboard tile, the dashboard whose filters it keeps. Null otherwise.
+ * @nullable
+ */
+ dashboard_id?: number | null;
+ }
+
+ export interface PulsePins {
+ /** Numbers the person keeps at the start of the key numbers, in order. Suggestions fill the free places. Only the first 4 distinct keys are kept. At most 20 entries. */
+ pins: PulsePin[];
+ }
+
/**
* * `run` - Run
* * `skip` - Skip
@@ -129433,6 +129485,10 @@ export namespace Schemas {
* Filter by `last_modified_at < date_to`. Accepts absolute dates or relative strings.
*/
date_to?: string;
+ /**
+ * Comma-separated chart types, e.g. `ActionsLineGraph,ActionsBar`. Only returns trends and SQL insights shown as one of them. A trends insight with no chart type set counts as `ActionsLineGraph`.
+ */
+ display?: string;
/**
* Exclude Business intelligence worksheets from the insight list.
*/
diff --git a/services/mcp/src/generated/product_analytics/api.ts b/services/mcp/src/generated/product_analytics/api.ts
index 025d1acebd3a..14bd4bc24ecd 100644
--- a/services/mcp/src/generated/product_analytics/api.ts
+++ b/services/mcp/src/generated/product_analytics/api.ts
@@ -96,6 +96,12 @@ export const InsightsListQueryParams = () => zod.object({
.string()
.optional()
.describe('Filter by `last_modified_at < date_to`. Accepts absolute dates or relative strings.'),
+ display: zod
+ .string()
+ .optional()
+ .describe(
+ 'Comma-separated chart types, e.g. `ActionsLineGraph,ActionsBar`. Only returns trends and SQL insights shown as one of them. A trends insight with no chart type set counts as `ActionsLineGraph`.'
+ ),
exclude_bi: zod.boolean().optional().describe('Exclude Business intelligence worksheets from the insight list.'),
favorited: zod
.boolean()
diff --git a/services/mcp/src/tools/generated/product_analytics.ts b/services/mcp/src/tools/generated/product_analytics.ts
index 874ba75ed24c..72d41deaa21e 100644
--- a/services/mcp/src/tools/generated/product_analytics.ts
+++ b/services/mcp/src/tools/generated/product_analytics.ts
@@ -629,6 +629,7 @@ const insightsList = (): ToolBase<
dashboards: params.dashboards,
date_from: params.date_from,
date_to: params.date_to,
+ display: params.display,
exclude_bi: params.exclude_bi,
favorited: params.favorited,
include_dashboards: params.include_dashboards,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/insights-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/insights-list.json
index 19165b186ab5..f6d88c50f478 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/insights-list.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/insights-list.json
@@ -25,6 +25,10 @@
"description": "Filter by `last_modified_at < date_to`. Accepts absolute dates or relative strings.",
"type": "string"
},
+ "display": {
+ "description": "Comma-separated chart types, e.g. `ActionsLineGraph,ActionsBar`. Only returns trends and SQL insights shown as one of them. A trends insight with no chart type set counts as `ActionsLineGraph`.",
+ "type": "string"
+ },
"exclude_bi": {
"description": "Exclude Business intelligence worksheets from the insight list.",
"type": "boolean"