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): bring back pinned key numbers and insight search (#129439)

Shy Alter341897f0314b
diff --git a/frontend/src/scenes/project-homepage/today/Today.scss b/frontend/src/scenes/project-homepage/today/Today.scss
index bd977e3d010c..fde695c94ec1 100644
--- a/frontend/src/scenes/project-homepage/today/Today.scss
+++ b/frontend/src/scenes/project-homepage/today/Today.scss
@@ -207,6 +207,22 @@ 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__metric {
display: flex;
flex-direction: column;
diff --git a/frontend/src/scenes/project-homepage/today/Today.stories.tsx b/frontend/src/scenes/project-homepage/today/Today.stories.tsx
index f90794c950c3..ea6c7339cdf7 100644
--- a/frontend/src/scenes/project-homepage/today/Today.stories.tsx
+++ b/frontend/src/scenes/project-homepage/today/Today.stories.tsx
@@ -725,6 +725,18 @@ 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' },
+]
+
+let storyPins: { key: string; name: string }[] = []
+let storyComputingCalls = 0
+let storyLastReady: HighlightsApi | null = null
+
const CHECKOUT_METRIC: HighlightsApi['pulse'][number] = {
...HIGHLIGHTS.pulse[0],
key: 'insight:chk01',
@@ -765,7 +777,30 @@ const REVENUE_METRIC: HighlightsApi['pulse'][number] = {
}
function storyHighlights(): HighlightsApi {
- return { ...HIGHLIGHTS, pulse: [...HIGHLIGHTS.pulse, CHECKOUT_METRIC, RETENTION_METRIC, REVENUE_METRIC] }
+ if (storyComputingCalls > 0) {
+ storyComputingCalls -= 1
+ return storyLastReady
+ ? { ...storyLastReady, status: 'computing' }
+ : { ...HIGHLIGHTS, status: 'computing', generated_at: null, pulse: [], items: [] }
+ }
+ const offered = [...HIGHLIGHTS.pulse, CHECKOUT_METRIC, RETENTION_METRIC, REVENUE_METRIC]
+ const chosen = storyPins.flatMap((pin) => offered.filter((metric) => metric.key === pin.key))
+ const suggested = offered.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], 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 = {
@@ -812,6 +847,12 @@ const meta: Meta = {
'/api/users/@me/integrations/': { results: [] },
'/api/users/@me/integrations/slack/linkable_workspaces/': { results: [] },
'/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,
@@ -910,6 +951,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: {
@@ -925,7 +974,7 @@ export default meta
type Story = StoryObj<{}>
-export const Home: Story = {}
+export const Home: Story = { decorators: [keepNumbers([])] }
export const HomeWithFrequentItems: Story = {
parameters: {
@@ -935,6 +984,7 @@ export const HomeWithFrequentItems: Story = {
},
},
decorators: [
+ keepNumbers([]),
mswDecorator({
get: {
'/api/projects/:team_id/file_system/frequent/': [
@@ -960,6 +1010,15 @@ export const HomeWithFrequentItems: Story = {
],
}
+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.test.tsx b/frontend/src/scenes/project-homepage/today/TodayHomePage.test.tsx
index 28b4a4fee1f7..fc4329635098 100644
--- a/frontend/src/scenes/project-homepage/today/TodayHomePage.test.tsx
+++ b/frontend/src/scenes/project-homepage/today/TodayHomePage.test.tsx
@@ -12,7 +12,7 @@ import { makeHighlights, makePulseMetric } from './todayTestFixtures'
jest.mock('kea', () => ({ ...jest.requireActual('kea'), useActions: jest.fn(), useValues: jest.fn() }))
jest.mock('./todayLogic', () => ({ todayLogic: { values: { homeScrollTop: null } }, reportIdFromPath: () => null }))
-jest.mock('./todayHighlightsLogic', () => ({ todayHighlightsLogic: {} }))
+jest.mock('./todayHighlightsLogic', () => ({ todayHighlightsLogic: {}, pulsePinLimitReason: () => undefined }))
jest.mock('./TodaySampleBanner', () => ({ TodaySampleBanner: () => null }))
jest.mock('./TodayForYou', () => ({ TodayForYou: () => null }))
jest.mock('./TodayRecents', () => ({ TodayRecents: () => null }))
@@ -87,6 +87,9 @@ describe('TodayHomePage loading', () => {
pulsePending: false,
pulseTiles: [] as typeof metrics,
pulseSlots: slots,
+ pulsePins: [],
+ pulsePinsLoaded: false,
+ pulsePinsUnavailableReason: null,
}
const actions = {
setReturnFocusReportId: jest.fn(),
diff --git a/frontend/src/scenes/project-homepage/today/TodayHomePage.tsx b/frontend/src/scenes/project-homepage/today/TodayHomePage.tsx
index 8ddd6f4c59ec..d34fe5c61773 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'
@@ -60,6 +61,7 @@ export function TodayHomePage(): JSX.Element {
pulsePending,
pulseTiles,
pulseSlots,
+ pulsePinsLoaded,
} = useValues(todayHighlightsLogic)
const { pulseViewMounted, pulseViewUpdated, pulseViewUnmounted } = useActions(todayHighlightsLogic)
const rootRef = useRef<HTMLDivElement>(null)
@@ -119,6 +121,7 @@ export function TodayHomePage(): JSX.Element {
</div>
<div className="TodayHome__metaRow">
<TodayMetaLine />
+ {!pulsePending && highlights && pulsePinsLoaded ? <TodayPulseEditor /> : null}
</div>
</section>
<div className="TodayHome__body">
diff --git a/frontend/src/scenes/project-homepage/today/TodayPulse.tsx b/frontend/src/scenes/project-homepage/today/TodayPulse.tsx
index 959d7f4e5a2e..82f0b01b7396 100644
--- a/frontend/src/scenes/project-homepage/today/TodayPulse.tsx
+++ b/frontend/src/scenes/project-homepage/today/TodayPulse.tsx
@@ -15,7 +15,7 @@ import type { CurrencyCode, TrendsFilter } from '~/queries/schema/schema-general
import type { HighlightMetricApi, PulseSlotApi } from 'products/today/frontend/generated/api.schemas'
import { TodayChange } from './TodayChange'
-import { todayHighlightsLogic } from './todayHighlightsLogic'
+import { pulsePinLimitReason, todayHighlightsLogic } from './todayHighlightsLogic'
import { todayNumber } from './todayNumbers'
import { TodayPulseCard } from './TodayPulseCard'
import { pulseChange } from './todayPulseFacts'
@@ -110,11 +110,13 @@ export function TodayPulse({ metrics, slots }: { metrics: HighlightMetricApi[];
interval: metric.interval,
})
)
- const { highlightsLoading, highlights, highlightsFailed } = useValues(todayHighlightsLogic)
+ const { highlightsLoading, highlights, highlightsFailed, pulsePins, pulsePinsUnavailableReason } =
+ useValues(todayHighlightsLogic)
const listRef = useRef<HTMLUListElement>(null)
useSettleOnReorder(listRef, cards.map((tile) => tile.key).join('|'))
const { baseCurrency } = useValues(teamLogic)
- const { pulseMetricOpened, pulseMetricPreviewed, hidePulseMetric, retryPulse } = useActions(todayHighlightsLogic)
+ const { pulseMetricOpened, pulseMetricPreviewed, hidePulseMetric, togglePulsePin, retryPulse } =
+ useActions(todayHighlightsLogic)
return (
<ul ref={listRef} className="TodayPulse" aria-label="Key numbers, against the period before">
{cards.map((slot, position) => {
@@ -168,6 +170,7 @@ export function TodayPulse({ metrics, slots }: { metrics: HighlightMetricApi[];
}
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 change = pulseChange(metric)
@@ -207,6 +210,16 @@ export function TodayPulse({ metrics, slots }: { metrics: HighlightMetricApi[];
tone={tone}
formatValue={metric.value_format ? formatValue : cardNumber}
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'
+ )
+ }
onHide={() => hidePulseMetric(metric, position)}
/>
}
diff --git a/frontend/src/scenes/project-homepage/today/TodayPulseCard.tsx b/frontend/src/scenes/project-homepage/today/TodayPulseCard.tsx
index 9da949196390..9d702066c219 100644
--- a/frontend/src/scenes/project-homepage/today/TodayPulseCard.tsx
+++ b/frontend/src/scenes/project-homepage/today/TodayPulseCard.tsx
@@ -25,6 +25,7 @@ import { todayNumber } from './todayNumbers'
import { pulseChange, pulsePeriodCaption, pulsePriorLabel, pulseWhy } from './todayPulseFacts'
import { TodayPulseMovers } from './TodayPulseMovers'
import { pulseOpenHandlers } from './todayPulseOpenHandlers'
+import { TodayPulsePinButton } from './TodayPulsePinButton'
import type { TodayTone } from './todayTone'
function openLabel(metric: HighlightMetricApi): string {
@@ -36,16 +37,22 @@ export function TodayPulseCard({
tone,
formatValue,
onOpen,
+ pinned,
+ pinDisabledReason,
+ onTogglePin,
onHide,
}: {
metric: HighlightMetricApi
tone: TodayTone
formatValue: (value: number) => string
onOpen: () => void
+ pinned: boolean
+ pinDisabledReason?: string
+ onTogglePin: () => void
onHide: () => void
}): JSX.Element {
const [whyOpen, setWhyOpen] = useState(false)
- const why = pulseWhy(metric)
+ const why = pinned ? 'You keep this number on your home. Change it with Edit.' : pulseWhy(metric)
const change = pulseChange(metric)
return (
<div className="TodayPulseCard flex flex-col" data-attr="today-pulse-card">
@@ -104,16 +111,23 @@ export function TodayPulseCard({
<span />
)}
<div className="-me-1.5 flex items-center">
- <Button
- size="icon-xs"
- aria-label="Hide from Today"
- tooltip="Hide from Today"
- onClick={onHide}
- className="text-muted-foreground"
- data-attr="today-pulse-card-hide"
- >
- <IconHide />
- </Button>
+ <TodayPulsePinButton
+ pinned={pinned}
+ disabledReason={pinDisabledReason}
+ onToggle={onTogglePin}
+ />
+ {!pinned && (
+ <Button
+ size="icon-xs"
+ aria-label="Hide from Today"
+ tooltip="Hide from Today"
+ onClick={onHide}
+ className="text-muted-foreground"
+ data-attr="today-pulse-card-hide"
+ >
+ <IconHide />
+ </Button>
+ )}
{why && (
<Tooltip>
<TooltipTrigger
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..271e88cc2c01
--- /dev/null
+++ b/frontend/src/scenes/project-homepage/today/TodayPulseEditor.tsx
@@ -0,0 +1,167 @@
+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,
+ pulseSlots,
+ 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(
+ pulseSlots.map(({ key, name }) => ({
+ key,
+ name,
+ dashboard_id:
+ pulseTiles.find((metric) => metric.key === key)?.dashboard_id ??
+ pulsePins.find((pin) => pin.key === key)?.dashboard_id ??
+ null,
+ }))
+ )
+ } else {
+ setSearch('')
+ }
+ }}
+ >
+ <PopoverTrigger
+ render={
+ <Button
+ size="sm"
+ className={cn('TodayPulse__edit', pulseSlots.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/TodayPulsePinButton.tsx b/frontend/src/scenes/project-homepage/today/TodayPulsePinButton.tsx
new file mode 100644
index 000000000000..9b6403f06be4
--- /dev/null
+++ b/frontend/src/scenes/project-homepage/today/TodayPulsePinButton.tsx
@@ -0,0 +1,28 @@
+import { IconPin, IconPinFilled } from '@posthog/icons'
+import { Button } from '@posthog/quill'
+
+export function TodayPulsePinButton({
+ pinned,
+ disabledReason,
+ onToggle,
+}: {
+ pinned: boolean
+ disabledReason?: string
+ onToggle: () => void
+}): JSX.Element {
+ const label = pinned ? 'Unpin from your home' : 'Pin to your home'
+ return (
+ <Button
+ size="icon-xs"
+ aria-label={label}
+ tooltip={label}
+ aria-pressed={pinned}
+ disabledReason={disabledReason}
+ onClick={onToggle}
+ className={pinned ? undefined : 'text-muted-foreground'}
+ data-attr="today-pulse-card-pin"
+ >
+ {pinned ? <IconPinFilled /> : <IconPin />}
+ </Button>
+ )
+}
diff --git a/frontend/src/scenes/project-homepage/today/todayHighlightsLogic.test.ts b/frontend/src/scenes/project-homepage/today/todayHighlightsLogic.test.ts
index 717cc94b3b29..3e086524f74c 100644
--- a/frontend/src/scenes/project-homepage/today/todayHighlightsLogic.test.ts
+++ b/frontend/src/scenes/project-homepage/today/todayHighlightsLogic.test.ts
@@ -110,6 +110,59 @@ describe('todayHighlightsLogic', () => {
expect(shown()).toEqual(['insight:c', 'insight:e', 'insight:a'])
})
+ it('waits for pins, puts pinned numbers first, keeps a hidden number the person pins, and marks a pin without a number', async () => {
+ let releasePins: () => void = () => undefined
+ useMocks({
+ get: {
+ '/api/projects/:team_id/today/pulse_pins/': () =>
+ new Promise((resolve) => {
+ releasePins = () =>
+ resolve([
+ 200,
+ {
+ pins: [
+ { key: 'insight:e', name: 'E', dashboard_id: null },
+ { key: 'insight:z', name: 'Z', dashboard_id: null },
+ ],
+ },
+ ])
+ }),
+ },
+ })
+ const pulse = ['a', 'b', 'c', 'd', 'e'].map((key) => makePulseMetric({ key: `insight:${key}` }))
+ highlightResponses = [[200, makeHighlights({ pulse, pins: [{ key: 'insight:z', status: 'unavailable' }] })]]
+ const logic = todayHighlightsLogic()
+ logic.mount()
+ const projectId = logic.values.currentProjectId
+ logic.actions.setHiddenPulseMetrics({ [`${projectId}:insight:e`]: true, [`${projectId}:insight:a`]: true })
+
+ await expectLogic(logic)
+ .toDispatchActions(['loadHighlightsSuccess'])
+ .toMatchValues({ pulseSlots: [], pulsePending: true })
+
+ releasePins()
+ await expectLogic(logic).toDispatchActions(['loadPulsePinsSuccess'])
+
+ expect(logic.values.pulseSlots.map((slot) => [slot.key, slot.status])).toEqual([
+ ['insight:e', 'ready'],
+ ['insight:z', 'error'],
+ ['insight:b', 'ready'],
+ ['insight:c', 'ready'],
+ ])
+
+ const [, b, c, d, e] = pulse
+ logic.actions.loadHighlightsSuccess(makeHighlights({ status: 'computing', pulse: [d, c, b, e], pins: [] }))
+ expect(logic.values.pulseSlots.map((slot) => [slot.key, slot.status])).toEqual([
+ ['insight:e', 'ready'],
+ ['insight:z', 'pending'],
+ ['insight:b', 'ready'],
+ ['insight:c', 'ready'],
+ ])
+
+ logic.actions.loadHighlightsSuccess(makeHighlights({ status: 'failed', pulse: [d, c, b, e], pins: [] }))
+ expect(logic.values.pulseSlots.map((slot) => slot.status)).toEqual(['ready', 'error', 'ready', 'ready'])
+ })
+
it.each([
{ status: 404, failed: false },
{ status: 500, failed: true },
@@ -231,6 +284,38 @@ describe('todayHighlightsLogic', () => {
logic.actions.pulseViewUnmounted()
})
+ it('waits for pins before it records an empty load', async () => {
+ let releasePins: () => void = () => undefined
+ useMocks({
+ get: {
+ '/api/projects/:team_id/today/pulse_pins/': () =>
+ new Promise((resolve) => {
+ releasePins = () =>
+ resolve([200, { pins: [{ key: 'insight:p', name: 'P', dashboard_id: null }] }])
+ }),
+ },
+ })
+ const capture = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined)
+ highlightResponses = [[200, makeHighlights({ pulse: [makePulseMetric({ key: 'insight:p' })] })]]
+ const logic = todayHighlightsLogic()
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadHighlightsSuccess'])
+ logic.actions.pulseViewMounted(false)
+ logic.actions.pulseViewUpdated()
+ const finishedBeforePins = capture.mock.calls.some(([event]) => event === 'today pulse load finished')
+
+ releasePins()
+ await expectLogic(logic).toDispatchActions(['loadPulsePinsSuccess'])
+ logic.actions.pulseViewUpdated()
+
+ expect(finishedBeforePins).toBe(false)
+ expect(capture).toHaveBeenCalledWith(
+ 'today pulse load finished',
+ expect.objectContaining({ outcome: 'ready', number_count: 1 })
+ )
+ logic.actions.pulseViewUnmounted()
+ })
+
it('records an already available number without waiting for another request', async () => {
const capture = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined)
highlightResponses = [[200, makeHighlights({ pulse: [makePulseMetric()] })]]
diff --git a/frontend/src/scenes/project-homepage/today/todayHighlightsLogic.ts b/frontend/src/scenes/project-homepage/today/todayHighlightsLogic.ts
index 821f842d3788..9b48f5501356 100644
--- a/frontend/src/scenes/project-homepage/today/todayHighlightsLogic.ts
+++ b/frontend/src/scenes/project-homepage/today/todayHighlightsLogic.ts
@@ -7,17 +7,31 @@ import { toast } from '@posthog/quill'
import { ApiError } from 'lib/api'
import { teamLogic } from 'scenes/teamLogic'
+import { urls } from 'scenes/urls'
-import { todayHighlightsRetrieve } from 'products/today/frontend/generated/api'
+import type { InsightShortId } from '~/types'
+
+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,
PulseSlotApi,
} 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
const PULSE_SLOW_MS = 30_000
@@ -42,7 +56,8 @@ function pulseLoadOutcome(
status: HighlightsApi['status'] | undefined,
failed: boolean,
unavailable: boolean,
- numberCount: number
+ numberCount: number,
+ pinsSettled: boolean
): 'request_error' | 'unavailable' | 'failed' | 'ready' | 'empty' | null {
if (failed) {
return 'request_error'
@@ -53,7 +68,13 @@ function pulseLoadOutcome(
if (status === 'failed') {
return 'failed'
}
- return status === 'ready' ? (numberCount > 0 ? 'ready' : 'empty') : null
+ if (status !== 'ready') {
+ return null
+ }
+ if (numberCount > 0) {
+ return 'ready'
+ }
+ return pinsSettled ? 'empty' : null
}
function capturePulseLoad(
@@ -87,12 +108,24 @@ function capturePulseLoad(
}
}
-function pulseKind(key: string): 'insight' | 'key_metric' {
- return key.startsWith('insight:') ? 'insight' : 'key_metric'
+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 hiddenHighlightKey(projectId: number | string, key: string): string {
- return `${projectId}:${key}`
+function pinnedSlot(pin: PulsePinApi, highlights: HighlightsApi | null): PulseSlotApi {
+ const shortId = pin.key.startsWith('insight:') ? pin.key.slice('insight:'.length) : null
+ return {
+ key: pin.key,
+ name: pin.name,
+ url: shortId ? urls.insightView(shortId as InsightShortId) : null,
+ interval: null,
+ status:
+ highlights?.pins.find((highlightPin) => highlightPin.key === pin.key)?.status === 'unavailable'
+ ? 'error'
+ : 'pending',
+ }
}
export interface PulsePlace {
@@ -125,10 +158,11 @@ function needsStandIn(place: PulsePlace, present: boolean, isHidden: (key: strin
export function placePulseSlots(
slots: PulseSlotApi[],
places: PulsePlace[],
- isHidden: (key: string) => boolean
+ isHidden: (key: string) => boolean,
+ limit: number = PULSE_TILES
): PulsePlacement {
const byKey = new Map(slots.map((slot) => [slot.key, slot]))
- const kept = places.slice(0, PULSE_TILES)
+ const kept = places.slice(0, limit)
const claimed = new Set(
kept
.flatMap((place) => [place.key, ...(place.standIn !== null ? [place.standIn] : [])])
@@ -165,13 +199,21 @@ export function placePulseSlots(
nextPlaces.push({ key: slot.key, standIn: null })
}
}
- for (const slot of spare.slice(0, PULSE_TILES - nextPlaces.length)) {
+ for (const slot of spare.slice(0, limit - nextPlaces.length)) {
shown.push(slot)
nextPlaces.push({ key: slot.key, standIn: null })
}
return { slots: shown, places: nextPlaces }
}
+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}`
+}
+
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface todayHighlightsLogicValues {
currentProjectId: number | string // teamLogic
@@ -185,7 +227,17 @@ export interface todayHighlightsLogicValues {
highlightsLoading: boolean
highlightsPending: boolean
highlightsWaitOver: boolean
+ pulseInsightResults: PulsePinApi[]
+ pulseInsightResultsLoading: boolean
+ pulseInsightSearchFailed: boolean
pulsePending: boolean
+ pulsePins: PulsePinApi[]
+ pulsePinsLoadFailed: boolean
+ pulsePinsLoaded: boolean
+ pulsePinsLoading: boolean
+ pulsePinsSaving: boolean
+ pulsePinsSettled: boolean
+ pulsePinsUnavailableReason: string | null
pulsePlacement: PulsePlacement
pulsePlaces: PulsePlace[]
pulseSlots: PulseSlotApi[]
@@ -230,6 +282,39 @@ export interface todayHighlightsLogicActions {
highlights: HighlightsApi | null
payload?: boolean
}
+ loadPulseInsightResults: (search: string) => string
+ loadPulseInsightResultsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadPulseInsightResultsSuccess: (
+ pulseInsightResults: PulsePinApi[],
+ payload?: string
+ ) => {
+ pulseInsightResults: PulsePinApi[]
+ 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
@@ -244,6 +329,12 @@ export interface todayHighlightsLogicActions {
metric: HighlightMetricApi
position: number
}
+ pulsePinsLoadGaveUp: () => {
+ value: true
+ }
+ pulsePinsSaved: () => {
+ value: true
+ }
pulseViewMounted: (sample: boolean) => {
sample: boolean
}
@@ -262,12 +353,22 @@ export interface todayHighlightsLogicActions {
setHiddenPulseMetrics: (hidden: Record<string, true>) => {
hidden: Record<string, true>
}
+ setPinnedPulseKeys: (metrics: PulsePinApi[]) => {
+ metrics: PulsePinApi[]
+ }
setPulsePlaces: (places: PulsePlace[]) => {
places: PulsePlace[]
}
stopWaitingForHighlights: () => {
value: true
}
+ togglePulsePin: (
+ pin: PulsePinApi,
+ source: PulsePinSource
+ ) => {
+ pin: PulsePinApi
+ source: PulsePinSource
+ }
unhideHighlight: (
item: HighlightItemApi,
position: number
@@ -287,13 +388,25 @@ 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
+ pulsePinsSettled: (pulsePinsLoaded: boolean, pulsePinsLoadFailed: boolean) => boolean
pulsePlacement: (
+ pulsePins: PulsePinApi[],
highlights: HighlightsApi | null,
hiddenPulseMetrics: Record<string, true>,
currentProjectId: number | string,
- pulsePlaces: PulsePlace[]
+ pulsePlaces: PulsePlace[],
+ pulsePinsSettled: boolean
) => PulsePlacement
- pulseSlots: (pulsePlacement: PulsePlacement, highlightsFailed: boolean) => PulseSlotApi[]
+ pulseSlots: (
+ pulsePlacement: PulsePlacement,
+ highlights: HighlightsApi | null,
+ highlightsFailed: boolean
+ ) => PulseSlotApi[]
pulseTiles: (highlights: HighlightsApi | null, pulseSlots: PulseSlotApi[]) => HighlightMetricApi[]
highlightsPending: (
highlights: HighlightsApi | null,
@@ -304,7 +417,8 @@ export interface todayHighlightsLogicMeta {
highlights: HighlightsApi | null,
highlightsPending: boolean,
pulseSlots: PulseSlotApi[],
- highlightsFailed: boolean
+ highlightsFailed: boolean,
+ pulsePinsSettled: boolean
) => boolean
doneHighlightKeys: (
highlights: HighlightsApi | null,
@@ -344,13 +458,59 @@ export const todayHighlightsLogic = kea<todayHighlightsLogicType>([
hidePulseMetric: (metric: HighlightMetricApi, position: number) => ({ metric, position }),
unhidePulseMetric: (metric: HighlightMetricApi, position: number) => ({ metric, position }),
setHiddenPulseMetrics: (hidden: Record<string, true>) => ({ hidden }),
+ setPinnedPulseKeys: (metrics: PulsePinApi[]) => ({ metrics }),
+ pulsePinsSaved: true,
+ pulseEditorOpened: true,
+ togglePulsePin: (pin: PulsePinApi, source: PulsePinSource) => ({ pin, source }),
+ pulsePinsLoadGaveUp: true,
setPulsePlaces: (places: PulsePlace[]) => ({ places }),
pulseViewMounted: (sample: boolean) => ({ sample }),
pulseViewUpdated: true,
retryPulse: true,
pulseViewUnmounted: (documentDeparture: boolean = false) => ({ documentDeparture }),
}),
- 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): PulsePinApi => ({
+ 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,
{
@@ -373,6 +533,16 @@ 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 },
+ ],
pulsePlaces: [
[] as PulsePlace[],
{
@@ -409,26 +579,68 @@ 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…',
+ ],
+ pulsePinsSettled: [
+ (s) => [s.pulsePinsLoaded, s.pulsePinsLoadFailed],
+ (pulsePinsLoaded: boolean, pulsePinsLoadFailed: boolean): boolean => pulsePinsLoaded || pulsePinsLoadFailed,
+ ],
pulsePlacement: [
- (s) => [s.highlights, s.hiddenPulseMetrics, s.currentProjectId, s.pulsePlaces],
+ (s) => [
+ s.pulsePins,
+ s.highlights,
+ s.hiddenPulseMetrics,
+ s.currentProjectId,
+ s.pulsePlaces,
+ s.pulsePinsSettled,
+ ],
(
+ pulsePins: PulsePinApi[],
highlights: HighlightsApi | null,
hiddenPulseMetrics: Record<string, true>,
currentProjectId: number | string,
- pulsePlaces: PulsePlace[]
- ): PulsePlacement =>
- placePulseSlots(
- pulseSlotsOf(highlights),
- pulsePlaces,
- (key) => !!hiddenPulseMetrics[hiddenHighlightKey(currentProjectId, key)]
- ),
+ pulsePlaces: PulsePlace[],
+ pulsePinsSettled: boolean
+ ): PulsePlacement => {
+ // Pins decide the order, so numbers wait for them rather than move after they arrive.
+ if (!pulsePinsSettled) {
+ return { slots: [], places: pulsePlaces }
+ }
+ const slots = pulseSlotsOf(highlights)
+ const pinnedKeys = new Set(pulsePins.map((pin) => pin.key))
+ const pinned = pulsePins
+ .slice(0, PULSE_TILES)
+ .map((pin) => slots.find((slot) => slot.key === pin.key) ?? pinnedSlot(pin, highlights))
+ const suggested = placePulseSlots(
+ slots.filter((slot) => !pinnedKeys.has(slot.key)),
+ pulsePlaces.filter((place) => !pinnedKeys.has(place.key)),
+ (key) => !!hiddenPulseMetrics[hiddenHighlightKey(currentProjectId, key)],
+ PULSE_TILES - pinned.length
+ )
+ return { slots: [...pinned, ...suggested.slots], places: suggested.places }
+ },
],
pulseSlots: [
- (s) => [s.pulsePlacement, s.highlightsFailed],
- (pulsePlacement: PulsePlacement, highlightsFailed: boolean): PulseSlotApi[] =>
+ (s) => [s.pulsePlacement, s.highlights, s.highlightsFailed],
+ (
+ pulsePlacement: PulsePlacement,
+ highlights: HighlightsApi | null,
+ highlightsFailed: boolean
+ ): PulseSlotApi[] =>
pulsePlacement.slots.map(
(slot): PulseSlotApi =>
- highlightsFailed && slot.status === 'pending' ? { ...slot, status: 'error' } : slot
+ (highlightsFailed || highlights?.status === 'failed') && slot.status === 'pending'
+ ? { ...slot, status: 'error' }
+ : slot
),
],
pulseTiles: [
@@ -445,16 +657,17 @@ export const todayHighlightsLogic = kea<todayHighlightsLogicType>([
: highlightsLoading),
],
pulsePending: [
- (s) => [s.highlights, s.highlightsPending, s.pulseSlots, s.highlightsFailed],
+ (s) => [s.highlights, s.highlightsPending, s.pulseSlots, s.highlightsFailed, s.pulsePinsSettled],
(
highlights: HighlightsApi | null,
highlightsPending: boolean,
pulseSlots: PulseSlotApi[],
- highlightsFailed: boolean
+ highlightsFailed: boolean,
+ pulsePinsSettled: boolean
): boolean =>
!highlightsFailed &&
pulseSlots.length === 0 &&
- (highlightsPending || highlights?.status === 'computing'),
+ (!pulsePinsSettled || highlightsPending || highlights?.status === 'computing'),
],
doneHighlightKeys: [
(s) => [s.highlights, s.hiddenHighlights, s.highlightsHiddenNow, s.currentProjectId],
@@ -485,13 +698,8 @@ export const todayHighlightsLogic = kea<todayHighlightsLogicType>([
}),
listeners(({ actions, values, cache }) => ({
pulseViewMounted: ({ sample }) => {
- actions.setPulsePlaces(
- placePulseSlots(
- pulseSlotsOf(values.highlights),
- [],
- (key) => !!values.hiddenPulseMetrics[hiddenHighlightKey(values.currentProjectId, key)]
- ).places
- )
+ actions.setPulsePlaces([])
+ actions.setPulsePlaces(values.pulsePlacement.places)
if (sample) {
return
}
@@ -573,7 +781,8 @@ export const todayHighlightsLogic = kea<todayHighlightsLogicType>([
values.highlights?.status,
values.highlightsFailed,
cache.highlightsUnavailable === true,
- numberCount
+ numberCount,
+ values.pulsePinsSettled
)
if (outcome) {
load.finished = true
@@ -611,15 +820,74 @@ export const todayHighlightsLogic = kea<todayHighlightsLogicType>([
load.requestCount += 1
}
},
- setHiddenPulseMetrics: () => {
- actions.setPulsePlaces(values.pulsePlacement.places)
- },
loadHighlightsFailure: () => {
const load = cache.pulseLoad as PulseLoad | undefined
if (load && !load.finished) {
load.errorCount += 1
}
},
+ setPinnedPulseKeys: async ({ metrics }, breakpoint) => {
+ actions.setPulsePlaces(values.pulsePlacement.places)
+ 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 })
+ },
+ loadPulsePinsSuccess: () => {
+ cache.pinsLoadRetries = 0
+ actions.setPulsePlaces(values.pulsePlacement.places)
+ },
+ setHiddenPulseMetrics: () => {
+ actions.setPulsePlaces(values.pulsePlacement.places)
+ },
+ 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')
+ },
hidePulseMetric: ({ metric, position }) => {
actions.setHiddenPulseMetrics({
...values.hiddenPulseMetrics,
@@ -734,12 +1002,14 @@ export const todayHighlightsLogic = kea<todayHighlightsLogicType>([
sources: highlights.items.map((item) => item.source),
pulse_count: values.pulseTiles.length,
pulse_candidate_count: highlights.pulse.length,
+ pinned_count: highlights.pins.length,
pulse_reasons: values.pulseTiles.map((metric) => metric.reason),
})
},
})),
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/products/today/backend/logic/highlights.py b/products/today/backend/logic/highlights.py
index 7cf72237518c..d47fdba32b9f 100644
--- a/products/today/backend/logic/highlights.py
+++ b/products/today/backend/logic/highlights.py
@@ -43,6 +43,8 @@ from ..temporal.inputs import (
FinalizeHighlightsInputs,
HighlightSourceInputs,
HighlightSourceResult,
+ PinnedNumber,
+ ResolvePinsInputs,
highlights_workflow_id,
)
from . import pulse_pins
@@ -61,6 +63,7 @@ MIN_SCORE = 0.2
PULSE_CANDIDATES = 6
URGENT_RISK_SCORE = 0.75
MINOR_OPPORTUNITY_SCORE = 0.4
+PINNED_SOURCE = "pinned"
_FINDINGS = TypeAdapter(HighlightFindings)
_HIGHLIGHTS = TypeAdapter(contracts.Highlights)
@@ -80,7 +83,12 @@ def get_highlights(
) -> 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)
progressive = progressive_pulse_enabled(user, team)
if progressive:
key = hashlib.sha256(f"{key}:progressive".encode()).hexdigest()[:32]
@@ -90,7 +98,6 @@ def get_highlights(
.order_by("-created_at")
)
latest = rows.first()
- # A row with a pins key puts pinned tiles first, so compute it again with suggestions only.
retry_failed = (
progressive
and refresh
@@ -99,8 +106,18 @@ def get_highlights(
and latest.status != HighlightsStatus.COMPUTING
and cache.add(f"today_highlights:retry:{team.id}:{user.id}", True, FAILED_CACHE_SECONDS)
)
- if latest is None or latest.pins_key or _is_due(latest, now) or retry_failed:
- _start(team, user, scopes, day, key, after=latest.id if latest else None, progressive=progressive)
+ if latest is None or latest.pins_key != pins_key or _is_due(latest, now) or retry_failed:
+ _start(
+ team,
+ user,
+ scopes,
+ day,
+ key,
+ pins,
+ pins_key,
+ after=latest.id if latest else None,
+ progressive=progressive,
+ )
status = HighlightsStatus.COMPUTING
else:
status = HighlightsStatus(latest.status)
@@ -115,7 +132,13 @@ def get_highlights(
if status == HighlightsStatus.COMPUTING and ready is not None and ready.id != latest.id:
old = _HIGHLIGHTS.validate_python(ready.content)
pending = {slot.key for slot in content.pulse_slots or [] if slot.status == PulseSlotStatus.PENDING}
- retained = [metric for metric in old.pulse if metric.key in pending]
+ shown = {metric.key for metric in content.pulse}
+ pin_keys = {pin.key for pin in pins}
+ retained = [
+ metric
+ for metric in old.pulse
+ if metric.key in pending or (metric.key in pin_keys and metric.key not in shown)
+ ]
retained_keys = {metric.key for metric in retained}
content = replace(
content,
@@ -146,6 +169,13 @@ def _key(team: Team, user: User, scopes: frozenset[str] | None) -> str:
return hashlib.sha256(f"{granted}:{restrictions}".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)
@@ -159,13 +189,17 @@ def _start(
scopes: frozenset[str] | None,
day: date,
key: str,
+ pins: list[PinnedNumber],
+ pins_key: str,
after: UUID | None,
progressive: bool = False,
) -> None:
- lock = f"today_highlights:start:{team.id}:{user.id}:{key}:{day.isoformat()}:{after}"
+ 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,
@@ -173,6 +207,7 @@ def _start(
local_day=day.isoformat(),
scopes=None if scopes is None else sorted(scopes),
source_names=[source.name for source in load_sources()],
+ pins=pins,
progressive=progressive,
)
try:
@@ -259,11 +294,14 @@ def publish_pulse(inputs: HighlightSourceInputs, found: HighlightFindings, slots
found = replace(found, pulse=tuple(metrics.values()))
slots = list({slot.key: slot for slot in [*previous.slots, *slots]}.values())
progress[inputs.source_name] = PulseSourceProgress(found=found, slots=slots)
+ pinned = _published_pins(progress)
content = build_highlights(
load_sources(),
{name: source.found for name, source in progress.items()},
Team.objects.get(id=inputs.team_id),
row.local_day,
+ pins=list(pinned),
+ pinned=pinned,
)
previous_slots = _HIGHLIGHTS.validate_python(row.content).pulse_slots if row.content else []
content = _pulse_content(content, progress, previous_slots or [])
@@ -272,6 +310,23 @@ def publish_pulse(inputs: HighlightSourceInputs, found: HighlightFindings, slots
row.save(update_fields=["content"])
+def publish_pinned(inputs: ResolvePinsInputs, metric: contracts.HighlightMetric) -> None:
+ source = HighlightSourceInputs(
+ team_id=inputs.team_id,
+ user_id=inputs.user_id,
+ local_day=inputs.local_day,
+ scopes=inputs.scopes,
+ source_name=PINNED_SOURCE,
+ highlights_id=inputs.highlights_id,
+ )
+ publish_pulse(source, HighlightFindings(pulse=(metric,)), [])
+
+
+def _published_pins(progress: Mapping[str, PulseSourceProgress]) -> dict[str, contracts.HighlightMetric]:
+ published = progress.get(PINNED_SOURCE)
+ return {metric.key: metric for metric in published.found.pulse} if published else {}
+
+
def run_source(inputs: HighlightSourceInputs) -> HighlightSourceResult:
source = next((source for source in load_sources() if source.name == inputs.source_name), None)
context = Context(
@@ -316,7 +371,10 @@ def finalize(inputs: FinalizeHighlightsInputs) -> None:
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)},
+ pinned={
+ **_published_pins(progress),
+ **{metric.key: metric for metric in PINNED_METRICS.validate_json(inputs.pinned)},
+ },
)
if "_pulse_sources" in row.content:
highlights = _pulse_content(
@@ -330,7 +388,7 @@ def finalize(inputs: FinalizeHighlightsInputs) -> None:
else HighlightsStatus.READY
)
row.content = _HIGHLIGHTS.dump_python(highlights, mode="json")
- row.failed_sources = bool(failed)
+ row.failed_sources = bool(failed) or inputs.pins_failed
row.ready_at = timezone.now()
row.save(update_fields=["status", "content", "failed_sources", "ready_at"])
if row.status == HighlightsStatus.READY:
diff --git a/products/today/backend/logic/pinned.py b/products/today/backend/logic/pinned.py
index 969d84d912e7..9f49f96ecc5a 100644
--- a/products/today/backend/logic/pinned.py
+++ b/products/today/backend/logic/pinned.py
@@ -1,6 +1,8 @@
+from collections.abc import Callable
from dataclasses import replace
from datetime import date
from functools import partial
+from time import monotonic
from pydantic import TypeAdapter
@@ -17,9 +19,12 @@ from .today_highlights.key_metrics import tile
from .today_highlights.routine import dashboard_tile_metric, insight_metric
PINNED_METRICS = TypeAdapter(list[contracts.HighlightMetric])
+PIN_SECONDS = 150
-def resolve_pins(inputs: ResolvePinsInputs) -> ResolvePinsResult:
+def resolve_pins(
+ inputs: ResolvePinsInputs, publish: Callable[[contracts.HighlightMetric], None] | None = None
+) -> ResolvePinsResult:
context = Context(
Team.objects.get(id=inputs.team_id),
User.objects.get(id=inputs.user_id),
@@ -27,27 +32,42 @@ def resolve_pins(inputs: ResolvePinsInputs) -> ResolvePinsResult:
None if inputs.scopes is None else frozenset(inputs.scopes),
)
metrics: list[contracts.HighlightMetric] = []
+ deadline = monotonic() + PIN_SECONDS
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 monotonic() >= deadline:
+ context.failures.append(pin.key)
+ continue
+ metric = context.guard(f"pinned {pin.key}", partial(_insight, context, pin, deadline), None)
if metric is not None:
metrics.append(replace(metric, reason=None))
+ if publish is not None:
+ publish(metrics[-1])
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
)
+ if found is None:
+ context.failures.append("pinned key metrics")
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())
+ for key in key_metrics:
+ if key in by_key:
+ metrics.append(replace(tile(by_key[key]), reason=None))
+ if publish is not None:
+ publish(metrics[-1])
+ return ResolvePinsResult(
+ found=PINNED_METRICS.dump_json(metrics).decode(),
+ failed=bool(context.failures) or monotonic() >= deadline,
+ )
-def _insight(context: Context, pin: PinnedNumber) -> contracts.HighlightMetric | None:
+def _insight(context: Context, pin: PinnedNumber, deadline: float) -> 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)
+ return dashboard_tile_metric(context, pin.dashboard_id, short_id, blocking=True, wait_until=deadline)
+ return insight_metric(context, short_id, blocking=True, wait_until=deadline)
diff --git a/products/today/backend/logic/today_highlights/routine.py b/products/today/backend/logic/today_highlights/routine.py
index 528d265a42bf..7f07a3f805ae 100644
--- a/products/today/backend/logic/today_highlights/routine.py
+++ b/products/today/backend/logic/today_highlights/routine.py
@@ -352,14 +352,19 @@ def _frecent_metric(
def dashboard_tile_metric(
- context: Context, dashboard_id: int, short_id: str, *, blocking: bool = False
+ context: Context,
+ dashboard_id: int,
+ short_id: str,
+ *,
+ blocking: bool = False,
+ wait_until: float | None = None,
) -> 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)
+ return _tile_metric(context, dashboard, dashboard.tiles[0], blocking=blocking, wait_until=wait_until)
def _tile_metric(
diff --git a/products/today/backend/temporal/activities.py b/products/today/backend/temporal/activities.py
index 60af3d5da772..a8ba990fd5a9 100644
--- a/products/today/backend/temporal/activities.py
+++ b/products/today/backend/temporal/activities.py
@@ -1,5 +1,7 @@
"""Temporal activities. Each one only calls logic. Payloads carry ids and small results only."""
+from functools import partial
+
import temporalio.activity
from posthog.sync import database_sync_to_async
@@ -21,7 +23,8 @@ async def run_highlight_source_activity(inputs: HighlightSourceInputs) -> Highli
@temporalio.activity.defn
async def resolve_pins_activity(inputs: ResolvePinsInputs) -> ResolvePinsResult:
- return await database_sync_to_async(pinned.resolve_pins, thread_sensitive=False)(inputs)
+ resolve = partial(pinned.resolve_pins, publish=partial(highlights.publish_pinned, inputs))
+ return await database_sync_to_async(resolve, thread_sensitive=False)(inputs)
@temporalio.activity.defn
diff --git a/products/today/backend/temporal/inputs.py b/products/today/backend/temporal/inputs.py
index 280b3a1285f9..2a6dd714c406 100644
--- a/products/today/backend/temporal/inputs.py
+++ b/products/today/backend/temporal/inputs.py
@@ -48,11 +48,13 @@ class ResolvePinsInputs:
local_day: str
scopes: list[str] | None
pins: list[PinnedNumber]
+ highlights_id: str | None = None
@dataclasses.dataclass(frozen=True)
class ResolvePinsResult:
found: str
+ failed: bool = False
@dataclasses.dataclass(frozen=True)
@@ -62,6 +64,7 @@ class FinalizeHighlightsInputs:
results: list[HighlightSourceResult]
pins: list[PinnedNumber] = dataclasses.field(default_factory=list)
pinned: str = "[]"
+ pins_failed: bool = False
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 c660e54c0879..ad618a17f719 100644
--- a/products/today/backend/temporal/workflows.py
+++ b/products/today/backend/temporal/workflows.py
@@ -18,6 +18,7 @@ with temporalio.workflow.unsafe.imports_passed_through():
HighlightSourceInputs,
HighlightSourceResult,
ResolvePinsInputs,
+ ResolvePinsResult,
)
HIGHLIGHT_SOURCE_TIMEOUT = timedelta(seconds=180)
@@ -36,7 +37,7 @@ class ComputeTodayHighlightsWorkflow(PostHogWorkflow):
if temporalio.workflow.patched(PINNED_NUMBERS_PATCH) and inputs.pins:
results, pinned = await asyncio.gather(sources, _resolve_pins(inputs))
else:
- results, pinned = await sources, "[]"
+ results, pinned = await sources, ResolvePinsResult(found="[]")
await temporalio.workflow.execute_activity(
finalize_highlights_activity,
FinalizeHighlightsInputs(
@@ -44,7 +45,8 @@ class ComputeTodayHighlightsWorkflow(PostHogWorkflow):
highlights_id=inputs.highlights_id,
results=list(results),
pins=inputs.pins,
- pinned=pinned,
+ pinned=pinned.found,
+ pins_failed=pinned.failed,
),
start_to_close_timeout=FINALIZE_HIGHLIGHTS_TIMEOUT,
retry_policy=temporalio.common.RetryPolicy(maximum_attempts=3),
@@ -72,7 +74,7 @@ async def _run_source(inputs: ComputeHighlightsInputs, source_name: str) -> High
return HighlightSourceResult(source_name=source_name, found=None, failed=True)
-async def _resolve_pins(inputs: ComputeHighlightsInputs) -> str:
+async def _resolve_pins(inputs: ComputeHighlightsInputs) -> ResolvePinsResult:
try:
result = await temporalio.workflow.execute_activity(
resolve_pins_activity,
@@ -82,10 +84,11 @@ async def _resolve_pins(inputs: ComputeHighlightsInputs) -> str:
local_day=inputs.local_day,
scopes=inputs.scopes,
pins=inputs.pins,
+ highlights_id=inputs.highlights_id if inputs.progressive else None,
),
start_to_close_timeout=HIGHLIGHT_SOURCE_TIMEOUT,
retry_policy=temporalio.common.RetryPolicy(maximum_attempts=1),
)
except ActivityError:
- return "[]"
- return result.found
+ return ResolvePinsResult(found="[]", failed=True)
+ return result
diff --git a/products/today/backend/tests/test_api.py b/products/today/backend/tests/test_api.py
index 9edfb998f04d..f48dc7b9d4b1 100644
--- a/products/today/backend/tests/test_api.py
+++ b/products/today/backend/tests/test_api.py
@@ -31,7 +31,6 @@ from products.signals.backend.models import SignalActorKind, SignalReport, Signa
from products.today.backend.facade.contracts import HighlightFindings, HighlightSource
from products.today.backend.logic import highlights, pinned
from products.today.backend.logic.jev import JevPick
-from products.today.backend.models import TodayHighlights
from products.today.backend.temporal.inputs import (
ComputeHighlightsInputs,
FinalizeHighlightsInputs,
@@ -467,25 +466,42 @@ class TestTodayHighlightsAPI(TodayTeamScopedTestMixin, APIBaseTest):
),
)
- def test_a_result_computed_with_pins_is_computed_again_with_suggestions_only(self) -> None:
+ 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"))
- TodayHighlights.objects.for_team(self.team.id).update(pins_key="pinned")
+ 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):
- self.client.put(
- f"/api/projects/{self.team.id}/today/pulse_pins/",
- {"pins": [{"key": "k2", "name": "k2"}]},
- format="json",
+ saved = self.client.put(
+ f"/api/projects/{self.team.id}/today/pulse_pins/", {"pins": pins}, format="json"
)
- clock.shift(timedelta(seconds=1))
+ read = self.client.get(f"/api/projects/{self.team.id}/today/pulse_pins/")
connect = _temporal()
- self._get(connect, pulse=("k1", "k2"))
+ 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(
- (connect.return_value.start_workflow.called, [m["key"] for m in after["pulse"]], after["pins"]),
- (True, ["k1", "k2"], []),
+ (
+ [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:
diff --git a/products/today/backend/tests/test_highlights.py b/products/today/backend/tests/test_highlights.py
index e8d5281e3ee7..6eedd0ecd3d1 100644
--- a/products/today/backend/tests/test_highlights.py
+++ b/products/today/backend/tests/test_highlights.py
@@ -37,19 +37,23 @@ from products.today.backend.facade.enums import (
HighlightInterval,
HighlightLabel,
HighlightMetricReason,
+ HighlightPinStatus,
HighlightPriority,
HighlightsStatus,
HighlightUnit,
PulseSlotStatus,
)
-from products.today.backend.logic import highlight_registry, highlight_types, highlights
+from products.today.backend.logic import highlight_registry, highlight_types, highlights, pulse_pins
from products.today.backend.logic.highlight_types import Context
from products.today.backend.logic.highlights import MAX_ITEMS, rank
+from products.today.backend.logic.pinned import PINNED_METRICS
from products.today.backend.models import TodayHighlights
from products.today.backend.temporal.inputs import (
FinalizeHighlightsInputs,
HighlightSourceInputs,
HighlightSourceResult,
+ PinnedNumber,
+ ResolvePinsInputs,
)
DAY = date(2026, 10, 13)
@@ -561,6 +565,103 @@ class TestProgressiveHighlights(BaseTest):
row.refresh_from_db()
self.assertEqual(row.content, before)
+ def test_a_pinned_number_shows_before_the_sources_finish_and_stays_after_the_pins_step_fails(self) -> None:
+ row = TodayHighlights.objects.for_team(self.team.id).create(
+ team_id=self.team.id, user_id=self.user.id, local_day=DAY, key="progress", pins_key="pins"
+ )
+ source = HighlightSourceInputs(
+ team_id=self.team.id,
+ user_id=self.user.id,
+ local_day=DAY.isoformat(),
+ scopes=None,
+ source_name="routine",
+ highlights_id=str(row.id),
+ )
+ pins = ResolvePinsInputs(
+ team_id=self.team.id,
+ user_id=self.user.id,
+ local_day=DAY.isoformat(),
+ scopes=None,
+ pins=[],
+ highlights_id=str(row.id),
+ )
+ highlights.publish_pulse(source, HighlightFindings(), [contracts.PulseSlot(key="slow", name="Slow")])
+ highlights.publish_pinned(pins, metric("kept"))
+ row.refresh_from_db()
+ partial = HIGHLIGHTS.validate_python(row.content)
+ highlights.finalize(
+ FinalizeHighlightsInputs(
+ team_id=self.team.id,
+ highlights_id=str(row.id),
+ results=[HighlightSourceResult(source_name="routine", found=None, failed=True)],
+ pins=[PinnedNumber(key="kept")],
+ )
+ )
+ row.refresh_from_db()
+ final = HIGHLIGHTS.validate_python(row.content)
+
+ self.assertEqual(
+ (
+ partial.status,
+ [(slot.key, slot.status) for slot in partial.pulse_slots or []],
+ [(pin.key, pin.status) for pin in final.pins],
+ [m.key for m in final.pulse],
+ ),
+ (
+ HighlightsStatus.COMPUTING,
+ [("kept", PulseSlotStatus.READY), ("slow", PulseSlotStatus.PENDING)],
+ [("kept", HighlightPinStatus.READY)],
+ ["kept"],
+ ),
+ )
+
+ @parameterized.expand([(False,), (True,)])
+ def test_a_failed_pins_step_marks_the_row_for_a_retry(self, pins_failed: bool) -> None:
+ row = TodayHighlights.objects.for_team(self.team.id).create(
+ team_id=self.team.id, user_id=self.user.id, local_day=DAY, key="pins-failed", pins_key="pins"
+ )
+ highlights.finalize(
+ FinalizeHighlightsInputs(
+ team_id=self.team.id,
+ highlights_id=str(row.id),
+ results=[HighlightSourceResult(source_name="routine", found="{}", failed=False)],
+ pins=[PinnedNumber(key="insight:slow")],
+ pins_failed=pins_failed,
+ )
+ )
+ row.refresh_from_db()
+
+ self.assertEqual(row.failed_sources, pins_failed)
+
+ def test_a_refresh_keeps_a_pinned_number_until_the_new_pins_step_publishes_it(self) -> None:
+ cache.clear()
+ pulse_pins.set_pins(team=self.team, user_id=self.user.id, pins=[contracts.PulsePin("insight:p", "P")])
+ connect = MagicMock()
+ connect.return_value.start_workflow = AsyncMock()
+ with (
+ patch.object(highlights, "progressive_pulse_enabled", return_value=True),
+ patch.object(highlights, "sync_connect", connect),
+ ):
+ highlights.get_highlights(team=self.team, user=self.user, scopes=None)
+ rows = TodayHighlights.objects.for_team(self.team.id)
+ first = rows.get()
+ highlights.finalize(
+ FinalizeHighlightsInputs(
+ team_id=self.team.id,
+ highlights_id=str(first.id),
+ results=[HighlightSourceResult(source_name="routine", found=None, failed=True)],
+ pins=[PinnedNumber(key="insight:p")],
+ pinned=PINNED_METRICS.dump_json([metric("insight:p")]).decode(),
+ )
+ )
+ rows.filter(id=first.id).update(created_at=timezone.now() - timedelta(seconds=1))
+ refreshing = highlights.get_highlights(team=self.team, user=self.user, scopes=None, refresh=True)
+
+ self.assertEqual(
+ (refreshing.status, rows.count(), [m.key for m in refreshing.pulse]),
+ (HighlightsStatus.COMPUTING, 2, ["insight:p"]),
+ )
+
@parameterized.expand([5, 6])
def test_progress_keeps_source_ranking_limit_and_dates_after_failure(self, routine_count: int) -> None:
row = TodayHighlights.objects.for_team(self.team.id).create(
diff --git a/products/today/backend/tests/test_pinned.py b/products/today/backend/tests/test_pinned.py
index 3c9cf62f219d..8062c133f733 100644
--- a/products/today/backend/tests/test_pinned.py
+++ b/products/today/backend/tests/test_pinned.py
@@ -82,33 +82,50 @@ class TestPinnedNumbers(BaseTest):
@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 cached insight", [PinnedNumber("insight:ready")], None, [], [("insight:ready", None)], False),
+ (
+ "an insight with no cached result",
+ [PinnedNumber("insight:cold")],
+ None,
+ [],
+ [("insight:cold", None)],
+ False,
+ ),
+ ("an insight whose query fails", [PinnedNumber("insight:broken")], None, [], [], True),
(
"a tile pinned from a dashboard",
[PinnedNumber("insight:ready", dashboard_id=7)],
None,
[],
[("insight:ready", "/dashboard/7")],
+ False,
),
- ("a tile removed from its dashboard", [PinnedNumber("insight:ready", dashboard_id=8)], None, [], []),
+ ("a tile removed from its dashboard", [PinnedNumber("insight:ready", dashboard_id=8)], None, [], [], False),
(
"a key metric with no events in either week",
[PinnedNumber("quiet")],
None,
[key_metric("quiet", 0, 0)],
[("quiet", None)],
+ False,
+ ),
+ ("key metrics still being calculated", [PinnedNumber("quiet")], None, None, [], True),
+ ("key metrics that fail to load", [PinnedNumber("quiet")], None, ValueError("down"), [], True),
+ (
+ "a key without insight access",
+ [PinnedNumber("insight:ready")],
+ ["customer_analytics:read"],
+ [],
+ [],
+ False,
),
- ("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"],
[],
[],
+ False,
),
]
)
@@ -119,6 +136,7 @@ class TestPinnedNumbers(BaseTest):
scopes: list[str] | None,
key_metrics: list[KeyMetric] | Exception | None,
resolved: list[tuple[str, str | None]],
+ failed: bool,
) -> None:
def series(**kwargs: Any) -> InsightSeries | None:
if kwargs["short_id"] == "cold" and not kwargs.get("blocking"):
@@ -166,9 +184,29 @@ class TestPinnedNumbers(BaseTest):
)
self.assertEqual(
- [
- (metric.key, metric.url if metric.dashboard_id else None)
- for metric in METRICS.validate_json(result.found)
- ],
- resolved,
+ (
+ [
+ (metric.key, metric.url if metric.dashboard_id else None)
+ for metric in METRICS.validate_json(result.found)
+ ],
+ result.failed,
+ ),
+ (resolved, failed),
)
+
+ def test_a_pin_after_the_deadline_is_skipped_and_marks_the_result_failed(self) -> None:
+ with (
+ patch.object(pinned, "PIN_SECONDS", 0),
+ patch.object(routine, "get_insight_series") as series,
+ ):
+ result = pinned.resolve_pins(
+ ResolvePinsInputs(
+ team_id=self.team.id,
+ user_id=self.user.id,
+ local_day=TODAY.isoformat(),
+ scopes=None,
+ pins=[PinnedNumber("insight:ready")],
+ )
+ )
+
+ self.assertEqual((METRICS.validate_json(result.found), result.failed, series.called), ([], True, False))
diff --git a/products/today/backend/tests/test_workflows.py b/products/today/backend/tests/test_workflows.py
index 8357785cdcfc..0a2bb63b55c9 100644
--- a/products/today/backend/tests/test_workflows.py
+++ b/products/today/backend/tests/test_workflows.py
@@ -109,7 +109,7 @@ async def test_sources_and_pins_are_resolved_once_and_finalized_together(
task_queue=settings.GENERAL_PURPOSE_TASK_QUEUE,
)
- assert (resolved, [(inputs.results, inputs.pins, inputs.pinned) for inputs in finalized]) == (
+ assert (resolved, [(inputs.results, inputs.pins, inputs.pinned, inputs.pins_failed) for inputs in finalized]) == (
asked,
[
(
@@ -119,6 +119,7 @@ async def test_sources_and_pins_are_resolved_once_and_finalized_together(
],
pins,
pinned,
+ pins_fail,
)
],
)