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): pick key numbers from what each person uses, watches, and builds (#129580)

Shy Alter1c560cff484a
diff --git a/frontend/src/scenes/project-homepage/today/todayPulseFacts.test.ts b/frontend/src/scenes/project-homepage/today/todayPulseFacts.test.ts
index 950211adf118..4c79bb62559a 100644
--- a/frontend/src/scenes/project-homepage/today/todayPulseFacts.test.ts
+++ b/frontend/src/scenes/project-homepage/today/todayPulseFacts.test.ts
@@ -27,6 +27,16 @@ describe('todayPulseFacts', () => {
{ reason: 'key_metric', opened_days: null, last_opened: null },
'It is a key metric for this project, set in Customer analytics.',
],
+ [
+ 'a watched insight never opened',
+ { reason: 'watched', opened_days: null, last_opened: null },
+ 'You get an alert or a subscription for this insight.',
+ ],
+ [
+ 'a built insight never opened',
+ { reason: 'built', opened_days: null, last_opened: null },
+ 'You created or edited this insight recently.',
+ ],
['a metric computed before reasons existed', { reason: null }, null],
] as const)('explains %s', (_name, overrides, expected) => {
expect(pulseWhy(makePulseMetric(overrides), today)).toBe(expected)
diff --git a/frontend/src/scenes/project-homepage/today/todayPulseFacts.ts b/frontend/src/scenes/project-homepage/today/todayPulseFacts.ts
index 85c467a84fae..6913a74aacee 100644
--- a/frontend/src/scenes/project-homepage/today/todayPulseFacts.ts
+++ b/frontend/src/scenes/project-homepage/today/todayPulseFacts.ts
@@ -33,22 +33,29 @@ function openedWhen(day: string, today: dayjs.Dayjs): string {
return `on ${dayjs(day).format('MMM D')}`
}
-export function pulseWhy(metric: HighlightMetricApi, today: dayjs.Dayjs = dayjs()): string | null {
- if (metric.reason === 'key_metric') {
- return 'It is a key metric for this project, set in Customer analytics.'
+function openedSubject(metric: HighlightMetricApi): string {
+ if (metric.reason !== 'dashboard') {
+ return 'this insight'
}
- if (metric.reason === 'popular') {
- return 'People in this project open this insight often.'
+ return metric.dashboard_name ? `the ${metric.dashboard_name} dashboard` : 'its dashboard'
+}
+
+const FIXED_WHY: Partial<Record<NonNullable<HighlightMetricApi['reason']>, string>> = {
+ key_metric: 'It is a key metric for this project, set in Customer analytics.',
+ popular: 'People in this project open this insight often.',
+ watched: 'You get an alert or a subscription for this insight.',
+ built: 'You created or edited this insight recently.',
+}
+
+export function pulseWhy(metric: HighlightMetricApi, today: dayjs.Dayjs = dayjs()): string | null {
+ const fixed = metric.reason ? FIXED_WHY[metric.reason] : undefined
+ if (fixed) {
+ return fixed
}
if (metric.reason !== 'routine' && metric.reason !== 'dashboard') {
return null
}
- const subject =
- metric.reason === 'dashboard'
- ? metric.dashboard_name
- ? `the ${metric.dashboard_name} dashboard`
- : 'its dashboard'
- : 'this insight'
+ const subject = openedSubject(metric)
const suffix = metric.reason === 'dashboard' ? ' This is the first chart on that dashboard.' : ''
if (!metric.last_opened) {
return `You open ${subject} often.${suffix}`
diff --git a/products/alerts/backend/facade/api.py b/products/alerts/backend/facade/api.py
index 199739acc2d5..b4590b5db737 100644
--- a/products/alerts/backend/facade/api.py
+++ b/products/alerts/backend/facade/api.py
@@ -13,7 +13,7 @@ from typing import Literal
from zoneinfo import ZoneInfo
from django.db import transaction
-from django.db.models import Q
+from django.db.models import Exists, OuterRef, Q
from django.utils import timezone
import structlog
@@ -50,7 +50,12 @@ from products.alerts.backend.llm_detector_limits import (
is_llm_detector_config,
llm_detector_access_error,
)
-from products.alerts.backend.models.alert import METRICS_INSIGHT_QUERY_FILTER, AlertCheck, AlertConfiguration
+from products.alerts.backend.models.alert import (
+ METRICS_INSIGHT_QUERY_FILTER,
+ AlertCheck,
+ AlertConfiguration,
+ AlertSubscription,
+)
from products.alerts_platform.backend.facade.contracts import InvalidPlatformAlertEdit
logger = structlog.get_logger(__name__)
@@ -251,6 +256,21 @@ def list_firing_alerts_created_by(
]
+WATCHED_ROWS_PER_INSIGHT = 4
+
+
+def insight_short_ids_watched_by(*, team_id: int, user_id: int, limit: int) -> list[str]:
+ """Short ids of insights with an enabled alert that the user created or subscribes to, newest alert first."""
+ follows = AlertSubscription.objects.filter(alert_configuration=OuterRef("pk"), user_id=user_id, subscribed=True)
+ rows = (
+ AlertConfiguration.objects.filter(team_id=team_id, enabled=True, insight__deleted=False)
+ .filter(Q(created_by_id=user_id) | Exists(follows))
+ .order_by("-created_at")
+ .values_list("insight__short_id", flat=True)[: limit * WATCHED_ROWS_PER_INSIGHT]
+ )
+ return list(dict.fromkeys(rows))[:limit]
+
+
def assign_alert_owner(*, team_id: int, alert_id: uuid.UUID, user: User, was_impersonated: bool) -> None:
"""Make `user` the owner of the alert and record the takeover in the activity log.
diff --git a/products/alerts/backend/tests/test_facade.py b/products/alerts/backend/tests/test_facade.py
index 8d2397cec18e..1ca0734bd8c1 100644
--- a/products/alerts/backend/tests/test_facade.py
+++ b/products/alerts/backend/tests/test_facade.py
@@ -6,12 +6,12 @@ from posthog.test.base import BaseTest
from parameterized import parameterized
from posthog.constants import AvailableFeature
-from posthog.models import OrganizationMembership, Team
+from posthog.models import OrganizationMembership, Team, User
from posthog.schema_enums import AlertState
from products.access_control.backend.models.access_control import AccessControl
from products.alerts.backend.facade import api, contracts
-from products.alerts.backend.models.alert import AlertConfiguration
+from products.alerts.backend.models.alert import AlertConfiguration, AlertSubscription
from products.product_analytics.backend.facade.models import Insight
@@ -122,3 +122,29 @@ class TestListFiringAlertsCreatedBy(BaseTest):
self._alert(self.team, {"query": query}, {})
assert len(self._firing(include_metrics_insights)) == (1 if listed else 0)
+
+
+class TestInsightShortIdsWatchedBy(BaseTest):
+ def test_lists_enabled_alerts_you_created_or_subscribe_to(self) -> None:
+ other = self._user("[email protected]")
+ rows = {
+ "created": (self.user, True, None),
+ "subscribed": (other, True, True),
+ "unsubscribed": (other, True, False),
+ "disabled": (self.user, False, None),
+ "someone_else": (other, True, None),
+ }
+ for name, (creator, enabled, subscribed) in rows.items():
+ insight = Insight.objects.create(team=self.team, name=name, short_id=name[:12])
+ alert = AlertConfiguration.objects.create(
+ team=self.team, insight=insight, name=name, enabled=enabled, created_by=creator
+ )
+ if subscribed is not None:
+ AlertSubscription.objects.create(alert_configuration=alert, user=self.user, subscribed=subscribed)
+
+ found = api.insight_short_ids_watched_by(team_id=self.team.id, user_id=self.user.id, limit=10)
+
+ assert sorted(found) == ["created", "subscribed"]
+
+ def _user(self, email: str) -> User:
+ return User.objects.create_and_join(self.organization, email, None)
diff --git a/products/product_analytics/backend/facade/api.py b/products/product_analytics/backend/facade/api.py
index bc104f537183..1ac9b8f1f283 100644
--- a/products/product_analytics/backend/facade/api.py
+++ b/products/product_analytics/backend/facade/api.py
@@ -17,7 +17,7 @@ from typing import TYPE_CHECKING, Any
from uuid import UUID
from django.db import transaction
-from django.db.models import QuerySet
+from django.db.models import Q, QuerySet
from posthog.models import Team, User
@@ -128,6 +128,19 @@ def recently_viewed_insights(*, team_id: int, user_id: int, limit: int) -> list[
return logic.recently_viewed_insights(team_id=team_id, user_id=user_id, limit=limit)
+def insight_short_ids_built_by(*, team: Team, user_id: int, since: datetime, limit: int) -> list[str]:
+ """Short ids of saved insights in the project that the user created or last edited since `since`, newest first."""
+ return list(
+ Insight.objects.filter(team__project_id=team.project_id, deleted=False, saved=True)
+ .filter(
+ Q(created_by_id=user_id, created_at__gte=since)
+ | Q(last_modified_by_id=user_id, last_modified_at__gte=since)
+ )
+ .order_by("-last_modified_at")
+ .values_list("short_id", flat=True)[:limit]
+ )
+
+
def insights_including_soft_deleted_for_team(*, team_id: int, insight_ids: Collection[int]) -> list[Insight]:
return logic.insights_including_soft_deleted_for_team(team_id=team_id, insight_ids=insight_ids)
diff --git a/products/product_analytics/backend/tests/test_facade.py b/products/product_analytics/backend/tests/test_facade.py
index a2d4b460c5bd..5e67b8bce1c5 100644
--- a/products/product_analytics/backend/tests/test_facade.py
+++ b/products/product_analytics/backend/tests/test_facade.py
@@ -14,8 +14,10 @@ from posthog.schema import TrendsQueryResponse
from posthog.clickhouse.client.connection import ClickHouseUser
from posthog.clickhouse.query_tagging import reset_query_tags, tag_queries
from posthog.models.team import Team
+from posthog.models.user import User
from products.product_analytics.backend.facade.api import (
+ insight_short_ids_built_by,
insight_variables_for_team,
insights_including_soft_deleted_for_team,
record_insight_view,
@@ -72,6 +74,27 @@ class TestRecordInsightView(BaseTest):
class TestInsightReads(BaseTest):
+ @time_machine.travel(datetime(2026, 10, 13, 12, 0, tzinfo=UTC), tick=False)
+ def test_built_insights_are_recent_saved_ones_you_created_or_edited(self) -> None:
+ other = User.objects.create_and_join(self.organization, "[email protected]", None)
+ since = now() - timedelta(days=28)
+ old = now() - timedelta(days=40)
+ rows: dict[str, tuple[dict[str, object], datetime]] = {
+ "created": ({"created_by": self.user}, now()),
+ "edited": ({"created_by": other, "last_modified_by": self.user}, now()),
+ "old": ({"created_by": self.user, "last_modified_by": self.user}, old),
+ "unsaved": ({"created_by": self.user, "saved": False}, now()),
+ "deleted": ({"created_by": self.user, "deleted": True}, now()),
+ "theirs": ({"created_by": other, "last_modified_by": other}, now()),
+ }
+ for short_id, (fields, at) in rows.items():
+ insight = Insight.objects.create(team=self.team, short_id=short_id, **fields)
+ Insight.objects_including_soft_deleted.filter(id=insight.id).update(created_at=at, last_modified_at=at)
+
+ found = insight_short_ids_built_by(team=self.team, user_id=self.user.id, since=since, limit=10)
+
+ assert sorted(found) == ["created", "edited"]
+
def test_including_soft_deleted_insights_stays_scoped_to_the_team(self) -> None:
deleted_insight = Insight.objects.create(team=self.team, name="Deleted", deleted=True)
live_insight = Insight.objects.create(team=self.team, name="Live")
diff --git a/products/subscriptions/backend/facade/api.py b/products/subscriptions/backend/facade/api.py
index c19e1358a192..750f637f7766 100644
--- a/products/subscriptions/backend/facade/api.py
+++ b/products/subscriptions/backend/facade/api.py
@@ -158,6 +158,15 @@ def subscription_ids_in_team(*, team_id: int, subscription_ids: Collection[int])
return queries.subscription_ids_in_team(team_id=team_id, subscription_ids=subscription_ids)
+def insight_short_ids_subscribed_by(*, team_id: int, user_id: int, email: str, now: datetime, limit: int) -> list[str]:
+ """Short ids of insights in active subscriptions the user receives, newest subscription first.
+
+ Email subscriptions match the user's address among the recipients. Slack and Teams
+ subscriptions have no person recipient, so they match the user who created them.
+ """
+ return queries.insight_short_ids_subscribed_by(team_id=team_id, user_id=user_id, email=email, now=now, limit=limit)
+
+
def user_has_slack_subscription(*, team_id: int, user_id: int) -> bool:
"""Whether the user created a subscription that delivers to Slack in this team. A disabled one counts."""
return queries.user_has_slack_subscription(team_id=team_id, user_id=user_id)
diff --git a/products/subscriptions/backend/logic/queries.py b/products/subscriptions/backend/logic/queries.py
index f99e1e911390..9230c67ba42b 100644
--- a/products/subscriptions/backend/logic/queries.py
+++ b/products/subscriptions/backend/logic/queries.py
@@ -35,6 +35,34 @@ def subscription_ids_in_team(*, team_id: int, subscription_ids: Collection[int])
return set(Subscription.objects.filter(team_id=team_id, id__in=subscription_ids).values_list("id", flat=True))
+def insight_short_ids_subscribed_by(*, team_id: int, user_id: int, email: str, now: datetime, limit: int) -> list[str]:
+ email_target = Subscription.SubscriptionTarget.EMAIL
+ rows = (
+ Subscription.objects.filter(
+ team_id=team_id,
+ deleted=False,
+ enabled=True,
+ next_delivery_date__isnull=False,
+ insight__isnull=False,
+ insight__deleted=False,
+ )
+ .filter(Q(until_date__isnull=True) | Q(until_date__gt=now))
+ .filter(
+ Q(target_type=email_target, target_value__icontains=email)
+ | (~Q(target_type=email_target) & Q(created_by_id=user_id))
+ )
+ .order_by("-id")
+ .values_list("insight__short_id", "target_type", "target_value")[: limit * 4]
+ )
+ recipient = email.strip().lower()
+ received = (
+ short_id
+ for short_id, target_type, target_value in rows
+ if target_type != email_target or recipient in {address.strip().lower() for address in target_value.split(",")}
+ )
+ return list(dict.fromkeys(received))[:limit]
+
+
def user_has_slack_subscription(*, team_id: int, user_id: int) -> bool:
return Subscription.objects.filter(
team_id=team_id,
diff --git a/products/subscriptions/backend/tests/logic/test_queries.py b/products/subscriptions/backend/tests/logic/test_queries.py
new file mode 100644
index 000000000000..eb2c08ec7bdf
--- /dev/null
+++ b/products/subscriptions/backend/tests/logic/test_queries.py
@@ -0,0 +1,37 @@
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+from posthog.test.base import BaseTest
+
+from posthog.models import User
+
+from products.product_analytics.backend.facade.models import Insight
+from products.subscriptions.backend.facade.api import insight_short_ids_subscribed_by
+from products.subscriptions.backend.models.subscription import Subscription
+from products.subscriptions.backend.tests.subscriptions_test_factory import create_subscription
+
+
+class TestInsightShortIdsSubscribedBy(BaseTest):
+ def test_lists_active_insight_subscriptions_the_user_receives(self) -> None:
+ now = datetime(2026, 10, 13, 12, 0, tzinfo=UTC)
+ other = User.objects.create_and_join(self.organization, "[email protected]", None)
+ me = self.user.email
+ rows: dict[str, dict[str, Any]] = {
+ "mine": {"created_by": self.user, "target_value": me},
+ "sent_to_me": {"created_by": other, "target_value": f"[email protected], {me.upper()}"},
+ "my_slack": {"created_by": self.user, "target_type": "slack", "target_value": "C0123"},
+ "sent_by_me": {"created_by": self.user, "target_value": "[email protected]"},
+ "other_slack": {"created_by": other, "target_type": "slack", "target_value": "C0456"},
+ "paused": {"created_by": self.user, "target_value": me, "enabled": False},
+ "ended": {"created_by": self.user, "target_value": me, "until_date": now - timedelta(days=1)},
+ "deleted": {"created_by": self.user, "target_value": me, "deleted": True},
+ "exhausted": {"created_by": self.user, "target_value": me},
+ }
+ for short_id, fields in rows.items():
+ insight = Insight.objects.create(team=self.team, short_id=short_id[:12])
+ create_subscription(team=self.team, insight=insight, **fields)
+ Subscription.objects.filter(insight__short_id="exhausted").update(next_delivery_date=None)
+
+ found = insight_short_ids_subscribed_by(team_id=self.team.id, user_id=self.user.id, email=me, now=now, limit=10)
+
+ assert sorted(found) == ["mine", "my_slack", "sent_to_me"]
diff --git a/products/today/backend/facade/enums.py b/products/today/backend/facade/enums.py
index 038f0359c10b..28976d402399 100644
--- a/products/today/backend/facade/enums.py
+++ b/products/today/backend/facade/enums.py
@@ -58,6 +58,8 @@ class HighlightMetricReason(LabeledStrEnum):
DASHBOARD = "dashboard", "On a dashboard you open often"
KEY_METRIC = "key_metric", "Project key metric"
POPULAR = "popular", "Opened often in this project"
+ WATCHED = "watched", "You get updates on this"
+ BUILT = "built", "You created or edited this"
class HighlightPinStatus(LabeledStrEnum):
diff --git a/products/today/backend/logic/today_highlights/routine.py b/products/today/backend/logic/today_highlights/routine.py
index 7f07a3f805ae..5861a2a7f705 100644
--- a/products/today/backend/logic/today_highlights/routine.py
+++ b/products/today/backend/logic/today_highlights/routine.py
@@ -1,10 +1,9 @@
-from collections.abc import Collection, Iterable, Iterator, Sequence
+from collections.abc import Collection, Iterable, Sequence
from dataclasses import replace
from datetime import date, timedelta
from functools import partial
from time import monotonic, sleep
-from django.db.models import Count, Max
from django.utils import timezone
from posthog.dataclasses import frozen
@@ -12,6 +11,7 @@ from posthog.exceptions_capture import capture_exception
from posthog.models import FileSystemViewLog
from posthog.models.file_system.file_system_view_log import VIEW_DAYS_KEPT
+from products.alerts.backend.facade.api import insight_short_ids_watched_by
from products.dashboards.backend.facade.api import (
DashboardInsights,
DashboardInsightTile,
@@ -22,9 +22,11 @@ from products.product_analytics.backend.facade.api import (
get_insight_series,
insight_query_complete,
insight_series_supported,
+ insight_short_ids_built_by,
viewable_insight_definitions,
)
from products.product_analytics.backend.facade.contracts import InsightDashboardContext, InsightSeriesNotReady
+from products.subscriptions.backend.facade.api import insight_short_ids_subscribed_by
from ...facade import contracts
from ...facade.enums import HighlightInterval, HighlightMetricReason, HighlightUnit, PulseSlotStatus
@@ -35,14 +37,17 @@ from ..highlight_types import Context, Found, Source
FRECENCY_HALF_LIFE_DAYS = 14
FRECENCY_LOOKBACK_DAYS = VIEW_DAYS_KEPT
-FRECENCY_CANDIDATES = 8
PULSE_CANDIDATES = 6
BLOCKING_SECONDS = 150
-POPULAR_DAYS = 30
-POPULAR_CANDIDATES = 8
DASHBOARD_TILES_TRIED = 6
OPENED_DAYS_WINDOW = 14
MOVERS_SHOWN = 4
+REPEAT_DAYS = 3
+REPEAT_WINDOW_DAYS = 28
+RECENT_DAYS = 14
+BUILT_DAYS = 28
+SIGNAL_MIX = (3, 2, 2)
+SIGNAL_CANDIDATES = 12
@frozen
@@ -50,7 +55,7 @@ class ViewedItem:
kind: str
ref: str
days: frozenset[date]
- popular: bool = False
+ reason: HighlightMetricReason | None = None
@frozen
@@ -90,7 +95,7 @@ def _progressive_metrics(context: Context, excluded: Collection[str], budget: in
return []
deadline = monotonic() + BLOCKING_SECONDS
candidates: list[PulseCandidate] = []
- for item in _candidates(context, _frecent_views(context)[:FRECENCY_CANDIDATES]):
+ for item in _own_candidates(context):
if item.kind == "insight":
candidates.append(PulseCandidate(viewed=item, short_id=item.ref))
elif item.ref.isdigit():
@@ -138,12 +143,12 @@ def _progressive_metrics(context: Context, excluded: Collection[str], budget: in
metric = insight_metric(
context,
candidate.short_id,
- viewed=None if candidate.viewed.popular else candidate.viewed,
+ viewed=candidate.viewed,
+ reason=candidate.viewed.reason,
dashboard=_dashboard_context(candidate),
url=slots[key].url,
dashboard_name=dashboard.name if dashboard else None,
dashboard_id=dashboard.dashboard_id if dashboard else None,
- reason=HighlightMetricReason.POPULAR if candidate.viewed.popular else None,
raise_on_pending=True,
)
except InsightSeriesNotReady as error:
@@ -203,7 +208,7 @@ def _eligible_choices(
slot=contracts.PulseSlot(
key=key,
name=definition.name or "Untitled insight",
- reason=HighlightMetricReason.POPULAR if candidate.viewed.popular else HighlightMetricReason.ROUTINE,
+ reason=candidate.viewed.reason or HighlightMetricReason.ROUTINE,
url=f"/dashboard/{dashboard.dashboard_id}" if dashboard else f"/insights/{candidate.short_id}",
interval=HighlightInterval(interval)
if source.get("kind") == "TrendsQuery" and interval in HighlightInterval.values
@@ -240,7 +245,7 @@ def _frecent_metrics(context: Context, excluded: Collection[str], budget: int) -
deadline = monotonic() + BLOCKING_SECONDS
candidates: list[tuple[ViewedItem, contracts.HighlightMetric | None]] = []
available: set[str] = set()
- for item in _candidates(context, _frecent_views(context)[:FRECENCY_CANDIDATES]):
+ for item in _own_candidates(context):
shown = frozenset([*excluded, *available])
metric = context.guard(
f"frecent {item.kind} {item.ref}",
@@ -267,14 +272,69 @@ def _frecent_metrics(context: Context, excluded: Collection[str], budget: int) -
return metrics
-def _candidates(context: Context, own: list[ViewedItem]) -> Iterator[ViewedItem]:
- yield from own
- known = {item.ref for item in own if item.kind == "insight"}
- popular: list[str] = context.guard(
- "popular insights", partial(context.daily, "popular_insights", partial(_popular_refs, context)), []
+def _own_candidates(context: Context) -> list[ViewedItem]:
+ none: list[str] = []
+ used = [item for item in _frecent_views(context) if _repeated(item.days, context.today)]
+ alerted = context.guard(
+ "alerted insights",
+ partial(
+ insight_short_ids_watched_by, team_id=context.team.id, user_id=context.user.id, limit=SIGNAL_CANDIDATES
+ ),
+ none,
+ )
+ subscribed = context.guard(
+ "subscribed insights",
+ partial(
+ insight_short_ids_subscribed_by,
+ team_id=context.team.id,
+ user_id=context.user.id,
+ email=context.user.email,
+ now=timezone.now(),
+ limit=SIGNAL_CANDIDATES,
+ ),
+ none,
)
- for ref in [ref for ref in popular if ref not in known][:POPULAR_CANDIDATES]:
- yield ViewedItem(kind="insight", ref=ref, days=frozenset(), popular=True)
+ built = context.guard(
+ "built insights",
+ partial(
+ insight_short_ids_built_by,
+ team=context.team,
+ user_id=context.user.id,
+ since=timezone.now() - timedelta(days=BUILT_DAYS),
+ limit=SIGNAL_CANDIDATES,
+ ),
+ none,
+ )
+ watched = [*alerted, *subscribed]
+ groups = [
+ used,
+ [
+ ViewedItem(kind="insight", ref=ref, days=frozenset(), reason=HighlightMetricReason.WATCHED)
+ for ref in dict.fromkeys(watched)
+ ],
+ [ViewedItem(kind="insight", ref=ref, days=frozenset(), reason=HighlightMetricReason.BUILT) for ref in built],
+ ]
+ return _mixed(groups, SIGNAL_MIX)[:SIGNAL_CANDIDATES]
+
+
+def _repeated(view_days: Collection[date], today: date) -> bool:
+ ages = [(today - day).days for day in view_days]
+ return sum(0 <= age < REPEAT_WINDOW_DAYS for age in ages) >= REPEAT_DAYS and any(
+ 0 <= age < RECENT_DAYS for age in ages
+ )
+
+
+def _mixed(groups: Sequence[Sequence[ViewedItem]], quotas: Sequence[int]) -> list[ViewedItem]:
+ seen: set[tuple[str, str]] = set()
+ unique: list[list[ViewedItem]] = []
+ for group in groups:
+ fresh = [item for item in group if (item.kind, item.ref) not in seen]
+ seen.update((item.kind, item.ref) for item in fresh)
+ unique.append(fresh)
+ return [
+ *(item for group, quota in zip(unique, quotas) for item in group[:quota]),
+ *(item for group, quota in zip(unique, quotas) for item in group[quota:]),
+ ]
def _frecent_views(context: Context) -> list[ViewedItem]:
@@ -294,34 +354,19 @@ def _frecent_views(context: Context) -> list[ViewedItem]:
return [item for score, _last, item in scored if score > 0]
-def _popular_refs(context: Context) -> list[str]:
- rows = (
- FileSystemViewLog.objects.filter(
- team=context.team, type="insight", viewed_at__gte=timezone.now() - timedelta(days=POPULAR_DAYS)
- )
- .values("ref")
- .annotate(viewers=Count("user_id", distinct=True), last_viewed=Max("viewed_at"))
- .order_by("-viewers", "-last_viewed", "ref")[: POPULAR_CANDIDATES + FRECENCY_CANDIDATES]
- )
- return [row["ref"] for row in rows]
-
-
def _frecent_metric(
context: Context, item: ViewedItem, shown: frozenset[str], deadline: float, *, wait: bool = True
) -> contracts.HighlightMetric | None:
if item.kind == "insight":
if f"insight:{item.ref}" in shown:
return None
- if item.popular:
- return insight_metric(
- context,
- item.ref,
- reason=HighlightMetricReason.POPULAR,
- blocking=wait and monotonic() < deadline,
- wait_until=deadline,
- )
return insight_metric(
- context, item.ref, viewed=item, blocking=wait and monotonic() < deadline, wait_until=deadline
+ context,
+ item.ref,
+ viewed=item,
+ reason=item.reason,
+ blocking=wait and monotonic() < deadline,
+ wait_until=deadline,
)
if not item.ref.isdigit():
return None
diff --git a/products/today/backend/presentation/serializers.py b/products/today/backend/presentation/serializers.py
index 03a8337834c6..3dff6c7d0b65 100644
--- a/products/today/backend/presentation/serializers.py
+++ b/products/today/backend/presentation/serializers.py
@@ -369,7 +369,7 @@ class HighlightMetricSerializer(DataclassSerializer):
reason = serializers.ChoiceField(
choices=HighlightMetricReason.choices,
allow_null=True,
- help_text="Why the pulse suggests the metric: `routine` for an insight the person opens often, `dashboard` for a tile of a dashboard they open often, `key_metric` for a key metric of the project, `popular` for an insight that many people in the project open. Null for metrics computed before this field existed.",
+ help_text="Why the pulse suggests the metric: `routine` for an insight the person opens often, `dashboard` for a tile of a dashboard they open often, `key_metric` for a key metric of the project, `popular` for an insight that many people in the project open, `watched` for an insight the person gets an alert or a subscription for, `built` for an insight the person created or edited recently. Null for metrics computed before this field existed.",
)
dashboard_name = serializers.CharField(
allow_null=True,
diff --git a/products/today/backend/tests/test_highlight_insights.py b/products/today/backend/tests/test_highlight_insights.py
index 7e61ced5adc9..bc10d4679304 100644
--- a/products/today/backend/tests/test_highlight_insights.py
+++ b/products/today/backend/tests/test_highlight_insights.py
@@ -301,14 +301,14 @@ class TestRoutineInsights(BaseTest):
"a session",
None,
[
- ("insight:signups", "/dashboard/7", "Growth", 2, TODAY - timedelta(days=1)),
- ("insight:old", "/insights/old", None, 0, TODAY - timedelta(days=20)),
+ ("insight:signups", "/dashboard/7", "Growth", 3, TODAY - timedelta(days=1)),
+ ("insight:old", "/insights/old", None, 1, TODAY - timedelta(days=13)),
],
),
(
"a key without dashboard access",
frozenset({"insight:read"}),
- [("insight:old", "/insights/old", None, 0, TODAY - timedelta(days=20))],
+ [("insight:old", "/insights/old", None, 1, TODAY - timedelta(days=13))],
),
]
)
@@ -316,7 +316,7 @@ class TestRoutineInsights(BaseTest):
def test_the_pulse_shows_a_dashboard_opened_often_as_its_first_working_tile(
self, _name: str, scopes: frozenset[str] | None, expected: list[tuple[str, str, str | None, int, date]]
) -> None:
- for kind, ref, ages in (("insight", "old", (20,)), ("dashboard", "7", (1, 2))):
+ for kind, ref, ages in (("insight", "old", (13, 20, 22)), ("dashboard", "7", (1, 2, 3))):
FileSystemViewLog.objects.create(
team=self.team,
user=self.user,
@@ -357,7 +357,7 @@ class TestRoutineInsights(BaseTest):
self.assertEqual([m.movers for m in pulse], [[]] * len(expected))
@time_machine.travel("2026-10-13T12:00:00Z", tick=False)
- def test_a_habit_ranks_above_a_more_recent_single_open(self) -> None:
+ def test_a_habit_shows_and_a_more_recent_single_open_does_not(self) -> None:
for ref, ages in (("habit", range(2, 10)), ("fresh", (1,))):
FileSystemViewLog.objects.create(
team=self.team,
@@ -376,7 +376,7 @@ class TestRoutineInsights(BaseTest):
):
pulse = routine.find(Context(self.team, self.user, TODAY)).pulse
- self.assertEqual([m.key for m in pulse], ["insight:habit", "insight:fresh"])
+ self.assertEqual([m.key for m in pulse], ["insight:habit"])
@parameterized.expand(
[
@@ -396,7 +396,7 @@ class TestRoutineInsights(BaseTest):
user=self.user,
type=kind,
ref=ref,
- view_days=[TODAY - timedelta(days=age)],
+ view_days=[TODAY - timedelta(days=age + extra) for extra in (0, 1, 2)],
viewed_at=datetime.combine(TODAY - timedelta(days=age), time(12), tzinfo=UTC),
)
growth = DashboardInsights(
@@ -442,39 +442,40 @@ class TestRoutineInsights(BaseTest):
self.assertTrue(all(not blocking for _, blocking, _, at in queried if at > routine.BLOCKING_SECONDS))
@time_machine.travel("2026-10-13T12:00:00Z", tick=False)
- def test_a_person_with_few_views_also_sees_the_insights_the_project_opens_most(self) -> None:
- others = [User.objects.create_and_join(self.organization, f"viewer{i}@example.com", None) for i in range(2)]
- for user, ref, age in (
- (self.user, "mine", 1),
- (others[0], "mine", 1),
- (others[0], "shared", 1),
- (others[1], "shared", 2),
- (others[1], "once", 1),
- (others[0], "stale", 40),
- ):
+ def test_the_pulse_mixes_repeated_watched_and_built_insights_without_popular_ones(self) -> None:
+ other = User.objects.create_and_join(self.organization, "[email protected]", None)
+ for user, ref, ages in ((self.user, "habit", [1, 5, 9]), (self.user, "once", [1]), (other, "shared", [1])):
FileSystemViewLog.objects.create(
team=self.team,
user=user,
type="insight",
ref=ref,
- view_days=[TODAY - timedelta(days=age)],
- viewed_at=datetime.combine(TODAY - timedelta(days=age), time(12), tzinfo=UTC),
+ view_days=[TODAY - timedelta(days=age) for age in ages],
+ viewed_at=datetime.combine(TODAY - timedelta(days=min(ages)), time(12), tzinfo=UTC),
)
points = [(TODAY - timedelta(days=d), 2.0 if d <= 7 else 1.0) for d in range(14, 0, -1)]
- with patch.object(
- routine,
- "get_insight_series",
- side_effect=lambda **kwargs: insight({"opened": points}, short_id=kwargs["short_id"], name="Opened"),
+ with (
+ patch.object(
+ routine,
+ "get_insight_series",
+ side_effect=lambda **kwargs: insight({"opened": points}, short_id=kwargs["short_id"], name="Opened"),
+ ),
+ patch.object(routine, "insight_short_ids_watched_by", return_value=["alerted", "habit"]),
+ patch.object(routine, "insight_short_ids_subscribed_by", return_value=["subscribed"]),
+ patch.object(routine, "insight_short_ids_built_by", return_value=["b1", "b2", "b3"]),
):
pulse = routine.find(Context(self.team, self.user, TODAY)).pulse
self.assertEqual(
- [(m.key, m.reason, m.last_opened) for m in pulse],
+ [(m.key, m.reason) for m in pulse],
[
- ("insight:mine", "routine", TODAY - timedelta(days=1)),
- ("insight:shared", "popular", None),
- ("insight:once", "popular", None),
+ ("insight:habit", "routine"),
+ ("insight:alerted", "watched"),
+ ("insight:subscribed", "watched"),
+ ("insight:b1", "built"),
+ ("insight:b2", "built"),
+ ("insight:b3", "built"),
],
)
@@ -515,8 +516,7 @@ class TestProgressiveInsights(SimpleTestCase):
),
)
with (
- patch.object(routine, "_frecent_views", return_value=views),
- patch.object(routine, "_candidates", side_effect=lambda context, own: iter(own)),
+ patch.object(routine, "_own_candidates", return_value=views),
patch.object(routine, "viewable_insight_definitions", return_value=definitions),
patch.object(routine, "get_insight_series", side_effect=series),
patch.object(
@@ -590,8 +590,7 @@ class TestProgressiveInsights(SimpleTestCase):
),
)
with (
- patch.object(routine, "_frecent_views", return_value=views),
- patch.object(routine, "_candidates", side_effect=lambda context, own: iter(own)),
+ patch.object(routine, "_own_candidates", return_value=views),
patch.object(routine, "dashboard_insights", return_value=dashboard),
patch.object(routine, "viewable_insight_definitions", return_value=definitions),
patch.object(routine, "get_insight_series", side_effect=series),
@@ -645,8 +644,7 @@ class TestProgressiveInsights(SimpleTestCase):
),
)
with (
- patch.object(routine, "_frecent_views", return_value=[viewed]),
- patch.object(routine, "_candidates", side_effect=lambda context, own: iter(own)),
+ patch.object(routine, "_own_candidates", return_value=[viewed]),
patch.object(routine, "dashboard_insights", return_value=dashboard),
patch.object(routine, "viewable_insight_definitions", return_value=definitions),
patch.object(
diff --git a/products/today/frontend/generated/api.schemas.ts b/products/today/frontend/generated/api.schemas.ts
index 80e8b3211460..502b649c3979 100644
--- a/products/today/frontend/generated/api.schemas.ts
+++ b/products/today/frontend/generated/api.schemas.ts
@@ -97,6 +97,8 @@ export interface HighlightValueFormatApi {
* * `dashboard` - On a dashboard you open often
* * `key_metric` - Project key metric
* * `popular` - Opened often in this project
+ * * `watched` - You get updates on this
+ * * `built` - You created or edited this
*/
export type HighlightMetricReasonEnumApi =
(typeof HighlightMetricReasonEnumApi)[keyof typeof HighlightMetricReasonEnumApi]
@@ -106,6 +108,8 @@ export const HighlightMetricReasonEnumApi = {
Dashboard: 'dashboard',
KeyMetric: 'key_metric',
Popular: 'popular',
+ Watched: 'watched',
+ Built: 'built',
} as const
export interface HighlightMoverApi {
@@ -155,12 +159,14 @@ export interface HighlightMetricApi {
value_format: HighlightValueFormatApi | null
/** The first day of the period each value in `series` covers, in the project's timezone. Same length and order as `series`. */
period_starts: string[]
- /** Why the pulse suggests the metric: `routine` for an insight the person opens often, `dashboard` for a tile of a dashboard they open often, `key_metric` for a key metric of the project, `popular` for an insight that many people in the project open. Null for metrics computed before this field existed.
+ /** Why the pulse suggests the metric: `routine` for an insight the person opens often, `dashboard` for a tile of a dashboard they open often, `key_metric` for a key metric of the project, `popular` for an insight that many people in the project open, `watched` for an insight the person gets an alert or a subscription for, `built` for an insight the person created or edited recently. Null for metrics computed before this field existed.
*
* * `routine` - You open this often
* * `dashboard` - On a dashboard you open often
* * `key_metric` - Project key metric
- * * `popular` - Opened often in this project */
+ * * `popular` - Opened often in this project
+ * * `watched` - You get updates on this
+ * * `built` - You created or edited this */
reason: HighlightMetricReasonEnumApi | null
/**
* Name of the dashboard the tile comes from when `reason` is `dashboard`, else null.
@@ -212,7 +218,9 @@ export interface PulseSlotApi {
* * `routine` - You open this often
* * `dashboard` - On a dashboard you open often
* * `key_metric` - Project key metric
- * * `popular` - Opened often in this project */
+ * * `popular` - Opened often in this project
+ * * `watched` - You get updates on this
+ * * `built` - You created or edited this */
reason?: HighlightMetricReasonEnumApi | null
/** Stable key of the selected number. */
key: string
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 2af718ed9dcf..7bdd41856716 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -51785,6 +51785,8 @@ export namespace Schemas {
* * `dashboard` - On a dashboard you open often
* * `key_metric` - Project key metric
* * `popular` - Opened often in this project
+ * * `watched` - You get updates on this
+ * * `built` - You created or edited this
*/
export type HighlightMetricReasonEnum = typeof HighlightMetricReasonEnum[keyof typeof HighlightMetricReasonEnum];
@@ -51794,6 +51796,8 @@ export namespace Schemas {
Dashboard: 'dashboard',
KeyMetric: 'key_metric',
Popular: 'popular',
+ Watched: 'watched',
+ Built: 'built',
} as const;
export interface HighlightMover {
@@ -51843,12 +51847,14 @@ export namespace Schemas {
value_format: HighlightValueFormat | null;
/** The first day of the period each value in `series` covers, in the project's timezone. Same length and order as `series`. */
period_starts: string[];
- /** Why the pulse suggests the metric: `routine` for an insight the person opens often, `dashboard` for a tile of a dashboard they open often, `key_metric` for a key metric of the project, `popular` for an insight that many people in the project open. Null for metrics computed before this field existed.
+ /** Why the pulse suggests the metric: `routine` for an insight the person opens often, `dashboard` for a tile of a dashboard they open often, `key_metric` for a key metric of the project, `popular` for an insight that many people in the project open, `watched` for an insight the person gets an alert or a subscription for, `built` for an insight the person created or edited recently. Null for metrics computed before this field existed.
*
* * `routine` - You open this often
* * `dashboard` - On a dashboard you open often
* * `key_metric` - Project key metric
- * * `popular` - Opened often in this project */
+ * * `popular` - Opened often in this project
+ * * `watched` - You get updates on this
+ * * `built` - You created or edited this */
reason: HighlightMetricReasonEnum | null;
/**
* Name of the dashboard the tile comes from when `reason` is `dashboard`, else null.
@@ -51937,7 +51943,9 @@ export namespace Schemas {
* * `routine` - You open this often
* * `dashboard` - On a dashboard you open often
* * `key_metric` - Project key metric
- * * `popular` - Opened often in this project */
+ * * `popular` - Opened often in this project
+ * * `watched` - You get updates on this
+ * * `built` - You created or edited this */
reason?: HighlightMetricReasonEnum | null;
/** Stable key of the selected number. */
key: string;
diff --git a/tach.toml b/tach.toml
index a412a45144a0..7a0d9b41a387 100644
--- a/tach.toml
+++ b/tach.toml
@@ -1807,10 +1807,12 @@ depends_on = [
"ee",
"posthog",
"products.access_control",
+ "products.alerts",
"products.customer_analytics",
"products.dashboards",
"products.product_analytics",
"products.signals",
+ "products.subscriptions",
"products.tasks",
]
layer = "modules"