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): replace pulse pins with hide (#123672)

Peter Kirkham174b63a58c58
diff --git a/frontend/src/scenes/project-homepage/today/Today.scss b/frontend/src/scenes/project-homepage/today/Today.scss
index 43b28abb4770..695c115796ee 100644
--- a/frontend/src/scenes/project-homepage/today/Today.scss
+++ b/frontend/src/scenes/project-homepage/today/Today.scss
@@ -207,31 +207,6 @@ 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;
diff --git a/frontend/src/scenes/project-homepage/today/Today.stories.tsx b/frontend/src/scenes/project-homepage/today/Today.stories.tsx
index 6d34ca6b9324..67e98495249b 100644
--- a/frontend/src/scenes/project-homepage/today/Today.stories.tsx
+++ b/frontend/src/scenes/project-homepage/today/Today.stories.tsx
@@ -725,14 +725,6 @@ 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',
@@ -749,9 +741,6 @@ const CHECKOUT_METRIC: HighlightsApi['pulse'][number] = {
movers: [],
}
-let storyPins: { key: string; name: string }[] = []
-let storyComputingCalls = 0
-
const RETENTION_METRIC: HighlightsApi['pulse'][number] = {
...CHECKOUT_METRIC,
key: 'insight:ret01',
@@ -775,36 +764,8 @@ const REVENUE_METRIC: HighlightsApi['pulse'][number] = {
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 />
- }
+ return { ...HIGHLIGHTS, pulse: [...HIGHLIGHTS.pulse, CHECKOUT_METRIC, RETENTION_METRIC, REVENUE_METRIC] }
}
const meta: Meta = {
@@ -851,12 +812,6 @@ 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,
@@ -954,14 +909,6 @@ 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: {
@@ -977,7 +924,7 @@ export default meta
type Story = StoryObj<{}>
-export const Home: Story = { decorators: [keepNumbers([])] }
+export const Home: Story = {}
export const HomeWithFrequentItems: Story = {
parameters: {
@@ -988,7 +935,6 @@ export const HomeWithFrequentItems: Story = {
},
},
decorators: [
- keepNumbers([]),
mswDecorator({
get: {
'/api/projects/:team_id/file_system/frequent/': [
@@ -1025,15 +971,6 @@ export const HomeWithRecentRanking: 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.tsx b/frontend/src/scenes/project-homepage/today/TodayHomePage.tsx
index 3b206186a3c8..ba3fd1c35231 100644
--- a/frontend/src/scenes/project-homepage/today/TodayHomePage.tsx
+++ b/frontend/src/scenes/project-homepage/today/TodayHomePage.tsx
@@ -9,7 +9,6 @@ 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'
@@ -18,7 +17,7 @@ const DATE_FORMAT = new Intl.DateTimeFormat(undefined, { weekday: 'long', day: '
function TodayPulseSkeleton(): JSX.Element {
return (
<ul className="TodayPulse" aria-busy aria-label="Loading key numbers">
- {['w-14', 'w-16', 'w-20'].map((width) => (
+ {['w-14', 'w-20', 'w-16', 'w-24'].map((width) => (
<li key={width} className="TodayPulse__metric">
<span className="TodayPulse__name">
<Skeleton className={`inline-block h-3 align-middle ${width}`} />
@@ -28,6 +27,9 @@ function TodayPulseSkeleton(): JSX.Element {
<Skeleton className="inline-block h-4 w-28 align-middle" />
</span>
</span>
+ <span className="TodayPulse__spark">
+ <Skeleton className="h-3 w-full" />
+ </span>
</li>
))}
</ul>
@@ -55,8 +57,8 @@ export function TodayHomePage(): JSX.Element {
highlightsLoading,
highlightsFailed,
highlightsPending,
+ pulsePending,
pulseTiles,
- pulsePinsLoaded,
} = useValues(todayHighlightsLogic)
const { pulseViewMounted, pulseViewUpdated, pulseViewUnmounted } = useActions(todayHighlightsLogic)
const rootRef = useRef<HTMLDivElement>(null)
@@ -73,6 +75,7 @@ export function TodayHomePage(): JSX.Element {
highlightsLoading,
highlightsFailed,
highlightsPending,
+ pulsePending,
pulseTiles,
pulseViewUpdated,
currentProjectId,
@@ -114,14 +117,17 @@ export function TodayHomePage(): JSX.Element {
</div>
<div className="TodayHome__metaRow">
<TodayMetaLine />
- {!highlightsPending && highlights && pulsePinsLoaded ? <TodayPulseEditor /> : null}
</div>
</section>
<div className="TodayHome__body">
- {highlightsPending ? (
+ {pulsePending ? (
<TodayPulseSkeleton />
) : highlights && pulseTiles.length > 0 ? (
<TodayPulse metrics={pulseTiles} />
+ ) : highlights?.status === 'ready' ? (
+ <Text size="sm" variant="muted" render={<p />} className="m-0">
+ Key numbers show here when you or your team open a few trend insights.
+ </Text>
) : 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 78f8881af9dc..138ede5ea0a4 100644
--- a/frontend/src/scenes/project-homepage/today/TodayPulse.tsx
+++ b/frontend/src/scenes/project-homepage/today/TodayPulse.tsx
@@ -1,29 +1,19 @@
import { useActions, useValues } from 'kea'
import { type RefObject, Suspense, lazy, 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 { retryImport } from 'lib/utils/retryImport'
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 {
- type PulsePlaceholderTile,
- type TodayPulseTile,
- isPlaceholderTile,
- pulsePinLimitReason,
- todayHighlightsLogic,
-} from './todayHighlightsLogic'
+import { todayHighlightsLogic } from './todayHighlightsLogic'
import { todayNumber } from './todayNumbers'
import { TodayPulseCard } from './TodayPulseCard'
import { TodayPulseHoverCard } from './TodayPulseHoverCard'
@@ -73,42 +63,6 @@ function metricFormatter(metric: HighlightMetricApi, currency: CurrencyCode): (v
return (value) => formatAggregationAxisValue(trendsFilter, value, currency)
}
-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 {
@@ -137,30 +91,16 @@ function useSettleOnReorder(listRef: RefObject<HTMLUListElement>, order: string)
}, [order, listRef])
}
-export function TodayPulse({ metrics }: { metrics: TodayPulseTile[] }): JSX.Element {
+export function TodayPulse({ metrics }: { metrics: HighlightMetricApi[] }): JSX.Element {
const listRef = useRef<HTMLUListElement>(null)
useSettleOnReorder(listRef, metrics.map((tile) => tile.key).join('|'))
const { baseCurrency } = useValues(teamLogic)
- const { pulsePins, pulsePinsUnavailableReason } = useValues(todayHighlightsLogic)
- const { pulseMetricOpened, pulseMetricPreviewed, togglePulsePin, holdPulseOrder, releasePulseOrder } =
+ const { pulseMetricOpened, pulseMetricPreviewed, hidePulseMetric, holdPulseOrder, releasePulseOrder } =
useActions(todayHighlightsLogic)
return (
<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 = (
@@ -204,16 +144,7 @@ export function TodayPulse({ metrics }: { metrics: TodayPulseTile[] }): JSX.Elem
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'
- )
- }
+ 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 a3e64efcf12b..930bacad8942 100644
--- a/frontend/src/scenes/project-homepage/today/TodayPulseCard.tsx
+++ b/frontend/src/scenes/project-homepage/today/TodayPulseCard.tsx
@@ -1,6 +1,6 @@
import { Suspense, lazy, useState } from 'react'
-import { IconArrowRight, IconInfo, IconPin, IconPinFilled } from '@posthog/icons'
+import { IconArrowRight, IconHide, IconInfo } from '@posthog/icons'
import {
Button,
Collapsible,
@@ -49,22 +49,18 @@ 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 previous = metric.previous_value
const peak = pulsePeak(metric)
- const why = pinned ? 'You keep this number on your home. Change it with Edit.' : pulseWhy(metric)
+ const why = 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">
@@ -138,15 +134,13 @@ export function TodayPulseCard({
<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"
+ aria-label="Hide from Today"
+ tooltip="Hide from Today"
+ onClick={onHide}
+ className="text-muted-foreground"
+ data-attr="today-pulse-card-hide"
>
- {pinned ? <IconPinFilled /> : <IconPin />}
+ <IconHide />
</Button>
{why && (
<Tooltip>
diff --git a/frontend/src/scenes/project-homepage/today/TodayPulseEditor.tsx b/frontend/src/scenes/project-homepage/today/TodayPulseEditor.tsx
deleted file mode 100644
index 9852e9548250..000000000000
--- a/frontend/src/scenes/project-homepage/today/TodayPulseEditor.tsx
+++ /dev/null
@@ -1,157 +0,0 @@
-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/todayHighlightsLogic.test.ts b/frontend/src/scenes/project-homepage/today/todayHighlightsLogic.test.ts
index 07764be04775..4ad000d16a61 100644
--- a/frontend/src/scenes/project-homepage/today/todayHighlightsLogic.test.ts
+++ b/frontend/src/scenes/project-homepage/today/todayHighlightsLogic.test.ts
@@ -62,6 +62,26 @@ describe('todayHighlightsLogic', () => {
])
})
+ it('hides a pulse metric in this project only, fills its place with the next suggestion, and undoes the hide', async () => {
+ const capture = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined)
+ const pulse = ['a', 'b', 'c', 'd', 'e'].map((key) => makePulseMetric({ key: `insight:${key}` }))
+ highlightResponses = [[200, makeHighlights({ pulse })]]
+ const logic = todayHighlightsLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ const shown = (): string[] => logic.values.pulseTiles.map((metric) => metric.key)
+
+ logic.actions.setHiddenPulseMetrics({ '1:insight:a': true })
+ expect(shown()).toEqual(['insight:a', 'insight:b', 'insight:c', 'insight:d'])
+
+ logic.actions.hidePulseMetric(pulse[1], 1)
+ expect(shown()).toEqual(['insight:a', 'insight:c', 'insight:d', 'insight:e'])
+ expect(capture).toHaveBeenCalledWith('today pulse metric hidden', expect.objectContaining({ position: 1 }))
+
+ logic.actions.unhidePulseMetric(pulse[1], 1)
+ expect(shown()).toEqual(['insight:a', 'insight:b', 'insight:c', 'insight:d'])
+ })
+
it.each([
{ status: 404, failed: false },
{ status: 500, failed: true },
@@ -75,7 +95,7 @@ describe('todayHighlightsLogic', () => {
.toMatchValues({ highlights: null, highlightsFailed: failed, highlightsPending: false })
})
- it('shows the skeleton until there is content, keeps the last ready content while new highlights compute, and polls until they are ready', async () => {
+ it('shows the skeleton until there is content, keeps the pulse skeleton while an older result without tiles is replaced, and polls until ready', async () => {
jest.useFakeTimers()
const item = makeHighlightItem()
highlightResponses = [
@@ -86,17 +106,19 @@ describe('todayHighlightsLogic', () => {
const logic = todayHighlightsLogic()
logic.mount()
- await expectLogic(logic).toDispatchActions(['loadHighlightsSuccess']).toMatchValues({ highlightsPending: true })
+ await expectLogic(logic)
+ .toDispatchActions(['loadHighlightsSuccess'])
+ .toMatchValues({ highlightsPending: true, pulsePending: true })
await expectLogic(logic, () => {
jest.advanceTimersByTime(HIGHLIGHTS_POLL_MS)
})
.toDispatchActions(['loadHighlights', 'loadHighlightsSuccess'])
- .toMatchValues({ highlightsPending: false, forYouHighlights: [item] })
+ .toMatchValues({ highlightsPending: false, pulsePending: true, forYouHighlights: [item] })
await expectLogic(logic, () => {
jest.advanceTimersByTime(HIGHLIGHTS_POLL_MS)
})
.toDispatchActions(['loadHighlights', 'loadHighlightsSuccess'])
- .toMatchValues({ highlights: makeHighlights({ items: [item] }) })
+ .toMatchValues({ highlights: makeHighlights({ items: [item] }), pulsePending: false })
await jest.advanceTimersByTimeAsync(HIGHLIGHTS_POLL_MS * 3)
expect(highlightCalls).toBe(3)
diff --git a/frontend/src/scenes/project-homepage/today/todayHighlightsLogic.ts b/frontend/src/scenes/project-homepage/today/todayHighlightsLogic.ts
index 6324ba673047..cb90b0113876 100644
--- a/frontend/src/scenes/project-homepage/today/todayHighlightsLogic.ts
+++ b/frontend/src/scenes/project-homepage/today/todayHighlightsLogic.ts
@@ -9,26 +9,11 @@ import { ApiError } from 'lib/api'
import { FEATURE_FLAGS } from 'lib/constants'
import { teamLogic } from 'scenes/teamLogic'
-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'
+import { todayHighlightsRetrieve } from 'products/today/frontend/generated/api'
+import type { HighlightItemApi, HighlightMetricApi, HighlightsApi } 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
@@ -91,22 +76,6 @@ function capturePulseLoad(
}
}
-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'
}
@@ -121,26 +90,19 @@ export interface todayHighlightsLogicValues {
doneHighlightKeys: string[]
forYouHighlights: HighlightItemApi[]
hiddenHighlights: Record<string, string>
+ hiddenPulseMetrics: Record<string, true>
highlights: HighlightsApi | null
highlightsFailed: boolean
highlightsHiddenNow: string[]
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[]
+ pulsePending: boolean
+ pulseTiles: HighlightMetricApi[]
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -152,6 +114,13 @@ export interface todayHighlightsLogicActions {
item: HighlightItemApi
position: number
}
+ hidePulseMetric: (
+ metric: HighlightMetricApi,
+ position: number
+ ) => {
+ metric: HighlightMetricApi
+ position: number
+ }
highlightOpened: (
item: HighlightItemApi,
position: number
@@ -181,47 +150,6 @@ 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
@@ -236,12 +164,6 @@ export interface todayHighlightsLogicActions {
metric: HighlightMetricApi
position: number
}
- pulsePinsLoadGaveUp: () => {
- value: true
- }
- pulsePinsSaved: () => {
- value: true
- }
pulseViewMounted: (sample: boolean) => {
sample: boolean
}
@@ -257,19 +179,12 @@ export interface todayHighlightsLogicActions {
setHiddenHighlights: (hidden: Record<string, string>) => {
hidden: Record<string, string>
}
- setPinnedPulseKeys: (metrics: PulsePinApi[]) => {
- metrics: PulsePinApi[]
+ setHiddenPulseMetrics: (hidden: Record<string, true>) => {
+ hidden: Record<string, true>
}
stopWaitingForHighlights: () => {
value: true
}
- togglePulsePin: (
- pin: PulsePinApi,
- source: PulsePinSource
- ) => {
- pin: PulsePinApi
- source: PulsePinSource
- }
unhideHighlight: (
item: HighlightItemApi,
position: number
@@ -277,25 +192,29 @@ export interface todayHighlightsLogicActions {
item: HighlightItemApi
position: number
}
+ unhidePulseMetric: (
+ metric: HighlightMetricApi,
+ position: number
+ ) => {
+ metric: HighlightMetricApi
+ position: number
+ }
}
// 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,
+ hiddenPulseMetrics: Record<string, true>,
+ currentProjectId: number | string,
pulseOrderHeld: {
keys: string[]
owner: string
} | null
- ) => TodayPulseTile[]
+ ) => HighlightMetricApi[]
highlightsPending: (highlights: HighlightsApi | null, highlightsLoading: boolean) => boolean
+ pulsePending: (highlights: HighlightsApi | null, highlightsPending: boolean) => boolean
doneHighlightKeys: (
highlights: HighlightsApi | null,
hiddenHighlights: Record<string, string>,
@@ -331,57 +250,16 @@ 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 }),
+ hidePulseMetric: (metric: HighlightMetricApi, position: number) => ({ metric, position }),
+ unhidePulseMetric: (metric: HighlightMetricApi, position: number) => ({ metric, position }),
+ setHiddenPulseMetrics: (hidden: Record<string, true>) => ({ hidden }),
holdPulseOrder: (owner: string, keys: string[]) => ({ owner, keys }),
releasePulseOrder: (owner: string) => ({ owner }),
- pulsePinsLoadGaveUp: true,
pulseViewMounted: (sample: boolean) => ({ sample }),
pulseViewUpdated: true,
pulseViewUnmounted: (documentDeparture: boolean = false) => ({ documentDeparture }),
}),
- 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
- }
- },
- },
- ],
+ loaders(({ values }) => ({
highlights: [
null as HighlightsApi | null,
{
@@ -402,16 +280,6 @@ 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,
{
@@ -424,6 +292,11 @@ export const todayHighlightsLogic = kea<todayHighlightsLogicType>([
{ persist: true },
{ setHiddenHighlights: (_, { hidden }) => hidden },
],
+ hiddenPulseMetrics: [
+ {} as Record<string, true>,
+ { persist: true },
+ { setHiddenPulseMetrics: (_, { hidden }) => hidden },
+ ],
highlightsHiddenNow: [
[] as string[],
{
@@ -444,38 +317,17 @@ 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],
+ (s) => [s.highlights, s.hiddenPulseMetrics, s.currentProjectId, s.pulseOrderHeld],
(
- pulsePins: PulsePinApi[],
highlights: HighlightsApi | null,
+ hiddenPulseMetrics: Record<string, true>,
+ currentProjectId: number | string,
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)
+ ): HighlightMetricApi[] => {
+ const tiles = (highlights?.pulse ?? [])
+ .filter((metric) => !hiddenPulseMetrics[hiddenHighlightKey(currentProjectId, metric.key)])
+ .slice(0, PULSE_TILES)
if (!pulseOrderHeld) {
return tiles
}
@@ -492,6 +344,12 @@ export const todayHighlightsLogic = kea<todayHighlightsLogicType>([
(highlights: HighlightsApi | null, highlightsLoading: boolean): boolean =>
highlights ? highlights.status === 'computing' && highlights.generated_at === null : highlightsLoading,
],
+ pulsePending: [
+ (s) => [s.highlights, s.highlightsPending],
+ // An older result with no tiles is not worth showing while a new one computes.
+ (highlights: HighlightsApi | null, highlightsPending: boolean): boolean =>
+ highlightsPending || (highlights?.status === 'computing' && highlights.pulse.length === 0),
+ ],
doneHighlightKeys: [
(s) => [s.highlights, s.hiddenHighlights, s.highlightsHiddenNow, s.currentProjectId],
(
@@ -587,9 +445,7 @@ export const todayHighlightsLogic = kea<todayHighlightsLogicType>([
if (!load || load.finished) {
return
}
- const numberCount = values.highlightsPending
- ? 0
- : values.pulseTiles.filter((tile) => !isPlaceholderTile(tile)).length
+ const numberCount = values.highlightsPending ? 0 : values.pulseTiles.length
if (numberCount > 0 && load.firstNumberAt === null) {
load.firstNumberAt = performance.now()
capturePulseLoad('today pulse first number shown', load, { number_count: numberCount })
@@ -638,48 +494,31 @@ export const todayHighlightsLogic = kea<todayHighlightsLogicType>([
load.errorCount += 1
}
},
- 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,
+ hidePulseMetric: ({ metric, position }) => {
+ actions.releasePulseOrder(metric.key)
+ actions.setHiddenPulseMetrics({
+ ...values.hiddenPulseMetrics,
+ [hiddenHighlightKey(values.currentProjectId, metric.key)]: true,
+ })
+ posthog.capture('today pulse metric hidden', {
+ kind: pulseKind(metric.key),
+ reason: metric.reason,
+ position,
+ pulse_ranking: posthog.getFeatureFlag(FEATURE_FLAGS.TODAY_PULSE_RANKING) ?? null,
+ })
+ toast.success({
+ title: 'Hidden from Today',
+ action: { label: 'Undo', onClick: () => actions.unhidePulseMetric(metric, position) },
})
},
- pulseEditorOpened: () => {
- posthog.capture('today pulse editor opened', { kept_count: values.pulsePins.length })
+ unhidePulseMetric: ({ metric, position }) => {
+ const { [hiddenHighlightKey(values.currentProjectId, metric.key)]: _, ...rest } = values.hiddenPulseMetrics
+ actions.setHiddenPulseMetrics(rest)
+ posthog.capture('today pulse metric unhidden', {
+ kind: pulseKind(metric.key),
+ reason: metric.reason,
+ position,
+ })
},
hideHighlight: ({ item, position }) => {
const day = values.highlights?.day
@@ -736,20 +575,6 @@ export const todayHighlightsLogic = kea<todayHighlightsLogicType>([
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 }) => {
cache.highlightsUnavailable = highlights === null
const load = cache.pulseLoad as PulseLoad | undefined
@@ -777,16 +602,15 @@ export const todayHighlightsLogic = kea<todayHighlightsLogicType>([
risk_count: highlights.items.filter((item) => item.label === 'risk').length,
opportunity_count: highlights.items.filter((item) => item.label === 'opportunity').length,
sources: highlights.items.map((item) => item.source),
- pulse_count: highlights.pulse.length,
- pinned_count: highlights.pins.length,
- pulse_reasons: highlights.pulse.map((metric) => metric.reason),
+ pulse_count: values.pulseTiles.length,
+ pulse_candidate_count: highlights.pulse.length,
+ pulse_reasons: values.pulseTiles.map((metric) => metric.reason),
pulse_ranking: posthog.getFeatureFlag(FEATURE_FLAGS.TODAY_PULSE_RANKING) ?? null,
})
},
})),
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/todayPulseFacts.ts b/frontend/src/scenes/project-homepage/today/todayPulseFacts.ts
index e9b1e13ded3d..8b1c837f4dd2 100644
--- a/frontend/src/scenes/project-homepage/today/todayPulseFacts.ts
+++ b/frontend/src/scenes/project-homepage/today/todayPulseFacts.ts
@@ -63,6 +63,9 @@ export function pulseWhy(metric: HighlightMetricApi, today: dayjs.Dayjs = dayjs(
if (metric.reason === 'key_metric') {
return 'It is a key metric for this project, set in Customer analytics.'
}
+ if (metric.reason === 'popular') {
+ return 'People in this project open this insight often.'
+ }
if (metric.reason !== 'routine' && metric.reason !== 'dashboard') {
return null
}
diff --git a/products/today/backend/logic/highlights.py b/products/today/backend/logic/highlights.py
index 537297b920a7..7fe9a56cc47b 100644
--- a/products/today/backend/logic/highlights.py
+++ b/products/today/backend/logic/highlights.py
@@ -40,7 +40,6 @@ from ..temporal.inputs import (
FinalizeHighlightsInputs,
HighlightSourceInputs,
HighlightSourceResult,
- PinnedNumber,
highlights_workflow_id,
)
from . import pulse_pins
@@ -67,20 +66,16 @@ _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 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)
+ # A row with a pins key puts pinned tiles first, so compute it again with suggestions only.
+ if latest is None or latest.pins_key or _is_due(latest, now):
+ _start(team, user, scopes, day, key, after=latest.id if latest else None)
status = HighlightsStatus.COMPUTING
else:
status = HighlightsStatus(latest.status)
@@ -103,13 +98,6 @@ 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)
@@ -123,16 +111,12 @@ def _start(
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}"
+ lock = f"today_highlights:start:{team.id}:{user.id}:{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, pins_key=pins_key
- )
+ row = TodayHighlights.objects.for_team(team.id).create(team_id=team.id, user_id=user.id, local_day=day, key=key)
inputs = ComputeHighlightsInputs(
team_id=team.id,
user_id=user.id,
@@ -140,7 +124,6 @@ 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,
)
try:
asyncio.run(
diff --git a/products/today/backend/tests/test_api.py b/products/today/backend/tests/test_api.py
index 7b43ac9f2567..837c251c1a99 100644
--- a/products/today/backend/tests/test_api.py
+++ b/products/today/backend/tests/test_api.py
@@ -30,6 +30,7 @@ from products.signals.backend.models import SignalReport
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,
@@ -441,42 +442,25 @@ class TestTodayHighlightsAPI(TodayTeamScopedTestMixin, APIBaseTest):
),
)
- def test_pinned_numbers_lead_the_pulse_and_a_new_pin_starts_a_new_computation(self) -> None:
+ def test_a_result_computed_with_pins_is_computed_again_with_suggestions_only(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))
+ TodayHighlights.objects.for_team(self.team.id).update(pins_key="pinned")
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"
+ self.client.put(
+ f"/api/projects/{self.team.id}/today/pulse_pins/",
+ {"pins": [{"key": "k2", "name": "k2"}]},
+ format="json",
)
- read = self.client.get(f"/api/projects/{self.team.id}/today/pulse_pins/")
+ clock.shift(timedelta(seconds=1))
connect = _temporal()
- during = self._get(connect, pulse=("k1", "k2")).json()
+ self._get(connect, pulse=("k1", "k2"))
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")],
- ),
+ (connect.return_value.start_workflow.called, [m["key"] for m in after["pulse"]], after["pins"]),
+ (True, ["k1", "k2"], []),
)
def test_saving_too_many_pins_is_rejected(self) -> None: