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(signals): remove setup noise and repeated lines from activity summary inputs (#126919)

posthog[bot]0ad5f5bedf1f
diff --git a/products/signals/backend/activity_summary/computed.py b/products/signals/backend/activity_summary/computed.py
index 11b0bf42361d..77bf07331176 100644
--- a/products/signals/backend/activity_summary/computed.py
+++ b/products/signals/backend/activity_summary/computed.py
@@ -25,6 +25,7 @@ from products.signals.backend.activity_summary.render import (
cap_line,
clean_text,
is_auto_named,
+ is_unnamed,
person_activity,
scene_product,
scope_of,
@@ -35,6 +36,9 @@ from products.signals.backend.activity_summary.render import (
# Bump on any change to the shape or the meaning of a field, so a consumer can tell old rows apart.
COMPUTED_SCHEMA_VERSION = 1
MAX_OWNED = 20
+# Owned objects one type takes in the first pass, so a burst of insights cannot fill the list.
+MAX_OWNED_PER_TYPE = 8
+DASHBOARD_SCOPE = "Dashboard"
MAX_WATCHED = 20
# An object opened on fewer days than this is a visit, not something the person keeps an eye on.
MIN_WATCHED_OPEN_DAYS = 3
@@ -119,6 +123,64 @@ def _object_id(item: ActivityItem) -> str | None:
return item.item_id
+@frozen
+class _OwnedEntry:
+ scope: str
+ id: str
+ latest: ActivityItem
+ edit_days: int
+ created: bool
+ group_days: frozenset[datetime.date]
+ group_created: bool
+
+
+def _owned_entries(edits: dict[tuple[str, str], list[ActivityItem]]) -> list[_OwnedEntry]:
+ """One entry per type and name, the most edited first, at most `MAX_OWNED`.
+
+ Objects of one type with the same name share one entry, the one with the newest row. The API returns
+ `id`, `edit_days` and `created` together, so they all describe that object. Only the rank uses the
+ distinct days of the whole group, so ten copies edited on one day rank as one day of work.
+
+ A created dashboard ranks above the objects edited on as many days, such as the insights on it. The
+ first pass takes at most `MAX_OWNED_PER_TYPE` of a type, and the second fills the rest of the slots."""
+ merged: dict[tuple[str, str], list[tuple[str, list[ActivityItem]]]] = {}
+ for (scope, object_id), rows in edits.items():
+ latest = max(rows, key=lambda row: row.at)
+ merged.setdefault((scope, _name(latest.name or "").casefold()), []).append((object_id, rows))
+ entries: list[_OwnedEntry] = []
+ for (scope, _), objects in merged.items():
+ object_id, rows = max(objects, key=lambda pair: max(row.at for row in pair[1]))
+ group_rows = [row for _, object_rows in objects for row in object_rows]
+ entries.append(
+ _OwnedEntry(
+ scope=scope,
+ id=object_id,
+ latest=max(rows, key=lambda row: row.at),
+ edit_days=len({_day(row.at) for row in rows}),
+ created=any(row.activity == "created" for row in rows),
+ group_days=frozenset(_day(row.at) for row in group_rows),
+ group_created=any(row.activity == "created" for row in group_rows),
+ )
+ )
+ entries.sort(
+ key=lambda entry: (
+ -len(entry.group_days),
+ not (entry.scope == DASHBOARD_SCOPE and entry.group_created),
+ -entry.latest.at.timestamp(),
+ entry.scope,
+ entry.id,
+ )
+ )
+ per_type: Counter[str] = Counter()
+ first: list[_OwnedEntry] = []
+ for entry in entries:
+ if len(first) < MAX_OWNED and per_type[entry.scope] < MAX_OWNED_PER_TYPE:
+ per_type[entry.scope] += 1
+ first.append(entry)
+ rest = [entry for entry in entries if entry not in first][: MAX_OWNED - len(first)]
+ return [entry for entry in entries if entry in first or entry in rest]
+
+
def _ranked(counts: Counter[Product]) -> tuple[str, ...]:
return tuple(str(product) for product, _ in sorted(counts.items(), key=lambda pair: (-pair[1], pair[0])))
@@ -128,8 +190,8 @@ def compute_fields(
) -> ComputedFields:
"""The owned and watched objects, the product pages, the products and the task count of one window.
- `owned` holds the objects the person created or changed, the most edited first. `watched` holds
- the objects opened on `MIN_WATCHED_OPEN_DAYS` or more days, the most opened first. A product is in
+ `owned` holds the objects the person created or changed, in the order of `_owned_entries`. `watched`
+ holds the objects opened on `MIN_WATCHED_OPEN_DAYS` or more days, the most opened first. A product is in
`works_in` when the person changed something in it or tagged a task with it, and in `visits` when
they only opened its pages or objects."""
kept, _ = person_activity(activity, Counter(), keep_ticket_bursts=True)
@@ -142,26 +204,17 @@ def compute_fields(
edits.setdefault((item.scope, object_id), []).append(item)
work: Counter[Product] = Counter({product: len(days) for product, days in work_days.items()})
- owned_ranked = sorted(
- edits.items(),
- key=lambda entry: (
- -len({_day(row.at) for row in entry[1]}),
- -max(row.at for row in entry[1]).timestamp(),
- entry[0],
- ),
- )
owned: list[OwnedObject] = []
- for (scope, item_id), rows in owned_ranked[:MAX_OWNED]:
- latest = max(rows, key=lambda row: row.at)
+ for entry in _owned_entries(edits):
owned.append(
OwnedObject(
ref=f"o{len(owned) + 1}",
- type=_snake(scope),
- id=item_id,
- name=_name(latest.name or ""),
- edit_days=len({_day(row.at) for row in rows}),
- last_at=_day(latest.at).isoformat(),
- created=any(row.activity == "created" for row in rows),
+ type=_snake(entry.scope),
+ id=entry.id,
+ name=_name(entry.latest.name or ""),
+ edit_days=entry.edit_days,
+ last_at=_day(entry.latest.at).isoformat(),
+ created=entry.created,
)
)
@@ -181,7 +234,7 @@ def compute_fields(
pages[product] = (max(at, view.at), days | set(view.days))
continue
name = (view.name or "").strip()
- if not name or is_auto_named(name):
+ if is_unnamed(name) or is_auto_named(name):
continue
open_days = len(set(view.days))
if (product := scope_product(scope_of(view.type))) is not None:
diff --git a/products/signals/backend/activity_summary/logic.py b/products/signals/backend/activity_summary/logic.py
index 6a671b70a7bb..ce511fd2ede4 100644
--- a/products/signals/backend/activity_summary/logic.py
+++ b/products/signals/backend/activity_summary/logic.py
@@ -202,6 +202,7 @@ def _inputs_used(rendered: RenderedInput, limits: RenderLimits, mcp: McpRead | N
"tasks": rendered.n_tasks,
"activity_lines": rendered.n_activity_lines,
"view_lines": rendered.n_view_lines,
+ "page_units": rendered.n_page_units,
"input_chars": rendered.input_chars,
"intent_lines": rendered.intent_lines,
"intent_chars": rendered.intent_chars,
diff --git a/products/signals/backend/activity_summary/prompt.py b/products/signals/backend/activity_summary/prompt.py
index 3041ba1db87b..06e4297d47b6 100644
--- a/products/signals/backend/activity_summary/prompt.py
+++ b/products/signals/backend/activity_summary/prompt.py
@@ -12,7 +12,13 @@ from typing import Any
from django.db import models
-from products.signals.backend.activity_summary.render import PRODUCT_LABELS, PROFILE_MAX_CHARS, Product, cap_line
+from products.signals.backend.activity_summary.render import (
+ PRODUCT_LABELS,
+ PROFILE_MAX_CHARS,
+ Product,
+ cap_line,
+ days_text,
+)
PROMPT_VERSION = 7
@@ -24,6 +30,8 @@ MAX_HEADLINE_CHARS = 600
# The computed block sits outside the render budget, so it has its own caps. `max_update_cost_usd` counts them.
COMPUTED_LINE_CHARS = 200
COMPUTED_MAX_CHARS = 8000
+# A product page opened on fewer days than this is a visit, and its line says nothing.
+MIN_PAGE_OPEN_DAYS = 2
STRENGTHS = ("high", "medium", "low")
DEFAULT_STRENGTH = "low"
# Strings a model writes in place of a JSON null.
@@ -169,31 +177,43 @@ def _product_label(key: str) -> str:
def computed_lines(computed: Mapping[str, Any] | None) -> str:
"""The computed lists of `computed.py` with their refs, at most `COMPUTED_MAX_CHARS` long.
- The products come first, then one line per object or product page, so a cut drops the least used ones."""
+ The products come first, then one line per object or product page, so a cut drops the least used ones.
+ An object that is both owned and watched gets one line. A product page opened on fewer than
+ `MIN_PAGE_OPEN_DAYS` days gets no line, but its ref stays valid."""
if not computed:
return "None"
- lines: list[str] = []
products = computed.get("products", {})
+ product_lines: list[str] = []
for title, key in (("Products they work in", "works_in"), ("Products they only visit", "visits")):
if names := [_product_label(product) for product in products.get(key, [])]:
- lines.append(f"{title}: {', '.join(names)}")
+ product_lines.append(f"{title}: {', '.join(names)}")
+ watched = {item["ref"]: item for item in computed.get("watched", [])}
+ lines: list[str] = []
for item in computed.get("owned", []):
- created = ", created" if item["created"] else ""
- lines.append(
- f'- {item["ref"]} {item["type"]} "{item["name"]}": edited on {item["edit_days"]} days, last {item["last_at"]}{created}'
- )
- for item in computed.get("watched", []):
+ facts = [f"edited on {days_text(item['edit_days'])}"]
+ last_at = item["last_at"]
+ if (opened := watched.pop(item["ref"], None)) is not None:
+ facts.append(f"opened on {days_text(opened['open_days'])}")
+ last_at = max(last_at, opened["last_at"])
+ facts.append(f"last {last_at}")
+ if item["created"]:
+ facts.append("created")
+ lines.append(f'- {item["ref"]} {item["type"]} "{item["name"]}": {", ".join(facts)}')
+ for item in watched.values():
not_theirs = ", not theirs" if item["not_theirs"] else ""
lines.append(
- f'- {item["ref"]} {item["type"]} "{item["name"]}": opened on {item["open_days"]} days, last {item["last_at"]}{not_theirs}'
+ f'- {item["ref"]} {item["type"]} "{item["name"]}": opened on {days_text(item["open_days"])}, last {item["last_at"]}{not_theirs}'
)
for item in computed.get("pages", []):
+ if item["open_days"] < MIN_PAGE_OPEN_DAYS:
+ continue
lines.append(
- f"- {item['ref']} {_product_label(item['product'])} pages: opened on {item['open_days']} days, last {item['last_at']}"
+ f"- {item['ref']} {_product_label(item['product'])} pages: opened on {days_text(item['open_days'])}, last {item['last_at']}"
)
+ # The product lines have a bounded length, so they are not cut.
kept: list[str] = []
chars = 0
- for line in (cap_line(line, COMPUTED_LINE_CHARS) for line in lines):
+ for line in product_lines + [cap_line(line, COMPUTED_LINE_CHARS) for line in lines]:
if chars + len(line) + 1 > COMPUTED_MAX_CHARS:
break
kept.append(line)
diff --git a/products/signals/backend/activity_summary/queue.py b/products/signals/backend/activity_summary/queue.py
index e1f1261a8c2b..c99b647b4786 100644
--- a/products/signals/backend/activity_summary/queue.py
+++ b/products/signals/backend/activity_summary/queue.py
@@ -54,10 +54,12 @@ from products.signals.backend.activity_summary.render import (
MAX_LIMITS,
MAX_SUMMARY_CHARS,
NOISY_ACTIVITY_SCOPES,
+ PERSON_SCOPE,
RENDER_VERSION,
SANDBOX_PROMPT_TITLE_PREFIX,
SCENE_VIEW_TYPE,
SCOUT_CLIENT_PREFIX,
+ SETUP_SCOPES,
RenderLimits,
)
from products.signals.backend.activity_summary.summaries import DEFAULT_MODEL, MAX_ATTEMPTS, MODEL_PRICES, cost_usd
@@ -359,7 +361,10 @@ def _after_watermark(
def _activity_rows(
team_ids: list[int], start: datetime.datetime, end: datetime.datetime, after_watermark: bool
) -> _Pending:
- """Activity log rows per pair in [start, end), with the filters of `inputs.user_activity`."""
+ """Activity log rows per pair in [start, end), with the filters of `inputs.user_activity`.
+
+ Setup rows do not make a pair due, even with an intent. A setup row with an intent still renders
+ when the pair is due for another reason."""
rows = (
ActivityLog.objects.filter(
team_id__in=team_ids, user_id__isnull=False, created_at__gte=start, created_at__lt=end
@@ -368,6 +373,8 @@ def _activity_rows(
.exclude(was_impersonated=True)
.exclude(scope__in=NOISY_ACTIVITY_SCOPES)
.exclude(client__startswith=SCOUT_CLIENT_PREFIX)
+ .exclude(scope__in=SETUP_SCOPES)
+ .exclude(scope=PERSON_SCOPE, activity="deleted")
)
unit_count = Count("id")
if after_watermark:
diff --git a/products/signals/backend/activity_summary/render.py b/products/signals/backend/activity_summary/render.py
index 567d4a6e9c55..4b613f12b0b5 100644
--- a/products/signals/backend/activity_summary/render.py
+++ b/products/signals/backend/activity_summary/render.py
@@ -13,6 +13,7 @@ import math
import random
import hashlib
import datetime
+import functools
import dataclasses
from collections import Counter
from collections.abc import Iterable, Mapping, Sequence
@@ -104,12 +105,24 @@ _AUTO_NAME = re.compile(r"\b\d{4}-\d{2}-\d{2}\b|model report", re.IGNORECASE)
_EMAIL = re.compile(r"[\w.+-]+@[\w-]+(?:\.[\w-]+)+")
_URL = re.compile(r"<?https?://[^\s<>]+>?")
-# Long runs of word characters: a run that mixes letters and digits is an API key, session token,
-# hash or UUID. The digit and letter checks run in `_mask_token`, because lookaheads in the pattern
-# rescan the run at every word boundary inside it and take quadratic time on a long input.
-_WORD_RUN = re.compile(r"[\w-]{24,}")
+# Long runs of word characters. A run that mixes letters and digits is masked when one segment looks like
+# an API key, session token or hash, or when a long run does not read as a name. The checks run in
+# `_mask_token`, because lookaheads in the pattern rescan the run at every word boundary inside it and
+# take quadratic time on a long input.
+_WORD_RUN = re.compile(r"[\w-]{16,}")
+_RUN_SEPARATORS = re.compile(r"[-_]")
+MIN_SECRET_SEGMENT_CHARS = 16
+# Masking is the default for a run this long, because a URL-safe credential can have only short segments.
+MIN_SECRET_RUN_CHARS = 24
+# A name such as "new-onboarding-flow-q4-2026" has few segments with digits, and they are short.
+MAX_NAME_DIGIT_SEGMENTS = 2
+MAX_NAME_DIGIT_SEGMENT_CHARS = 4
+# UUID segments are shorter than `MIN_SECRET_SEGMENT_CHARS`, so they have their own pattern.
+_UUID = re.compile(r"\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b", re.IGNORECASE)
_DIGIT = re.compile(r"\d")
_LETTER = re.compile(r"[A-Za-z]")
+# A name that is only masks, digits and punctuation after `clean_text` names nothing.
+_MEANINGLESS_NAME = re.compile(r"(?:<token>|<email>|\d|[^\w<>]|_)*")
_WHITESPACE = re.compile(r"\s+")
# Inbox onboarding creates a scout config for each canonical scout, named after its skill.
@@ -120,11 +133,16 @@ API_KEY_SCOPES: frozenset[str] = frozenset({"PersonalAPIKey"})
# CI writes deploy markers as annotations through a personal API key.
ANNOTATION_SCOPE = "Annotation"
PERSONAL_API_KEY_CREDENTIAL = "personal_api_key"
-TEAM_SCOPE = "Team"
+# Project settings live on both scopes.
+TEAM_SETTINGS_SCOPES: frozenset[str] = frozenset({"Team", "Project"})
# Team settings rows without an intent are dropped when the person has at least this many: one change
# can be deliberate, but repeated ones come from setup flows.
MIN_TEAM_SETTINGS_ROWS = 2
TICKET_SCOPE = "Ticket"
+# Setup chores, such as Inbox settings, integrations and their diagnostics, are not work in the project.
+SETUP_SCOPES: frozenset[str] = frozenset({"SignalTeamConfig", "Integration", "ProjectSecretAPIKey", "ExportedAsset"})
+# Person deletes come from data cleanup, such as removing test users.
+PERSON_SCOPE = "Person"
# Changes to this many distinct tickets on one UTC day collapse to one line with a count.
MIN_TICKET_BURST = 3
# Changes of one kind to this many distinct objects of one type inside the window are a bulk job,
@@ -291,6 +309,7 @@ class Drop(StrEnum):
API_KEY_CHANGE = "api_key_change"
API_KEY_ANNOTATION = "api_key_annotation"
TEAM_SETTINGS = "team_settings"
+ SETUP_SCOPE = "setup_scope"
BULK_SAME_TYPE = "bulk_same_type"
TICKET_BURST = "ticket_burst"
REPEATED_TASK = "repeated_task"
@@ -418,15 +437,35 @@ class RenderedInput:
mcp_chars: int = 0
# MCP sessions that passed the named filters, before the caps.
mcp_pool: int = 0
+ # Products whose pages the person opened. They render in the computed block, not here, but count as units.
+ n_page_units: int = 0
@property
def units(self) -> int:
- return self.n_tasks + self.n_activity_lines + self.n_view_lines + self.n_mcp_lines
+ return self.n_tasks + self.n_activity_lines + self.n_view_lines + self.n_mcp_lines + self.n_page_units
+
+
+def _reads_as_name(segments: Sequence[str]) -> bool:
+ with_digits = [segment for segment in segments if _DIGIT.search(segment)]
+ if len(with_digits) > MAX_NAME_DIGIT_SEGMENTS:
+ return False
+ if any(len(segment) > MAX_NAME_DIGIT_SEGMENT_CHARS for segment in with_digits):
+ return False
+ # Random URL-safe text mixes cases inside a segment. The words of a name do not.
+ return all(segment in (segment.lower(), segment.upper(), segment.capitalize()) for segment in segments)
def _mask_token(match: re.Match[str]) -> str:
run = match.group()
- return "<token>" if _DIGIT.search(run) and _LETTER.search(run) else run
+ if not (_DIGIT.search(run) and _LETTER.search(run)):
+ return run
+ segments = _RUN_SEPARATORS.split(run)
+ for segment in segments:
+ if len(segment) >= MIN_SECRET_SEGMENT_CHARS and _DIGIT.search(segment) and _LETTER.search(segment):
+ return "<token>"
+ if len(run) >= MIN_SECRET_RUN_CHARS and not _reads_as_name(segments):
+ return "<token>"
+ return run
def _url_host(match: re.Match[str]) -> str:
@@ -459,6 +498,7 @@ def clean_text(text: str, max_chars: int) -> str:
text = bounded_raw(text, max_chars * RAW_TEXT_FACTOR)
text = _URL.sub(_url_host, text)
text = _EMAIL.sub("<email>", text)
+ text = _UUID.sub("<token>", text)
text = _WORD_RUN.sub(_mask_token, text)
return _WHITESPACE.sub(" ", text).strip()[:max_chars].strip()
@@ -619,12 +659,17 @@ def _usable_parents(parents: Sequence[Parent]) -> list[Parent]:
return usable
+def _day_span(rows: Sequence[ActivityItem]) -> str:
+ """The UTC day of the rows, or the first and the last day when they span more than one."""
+ first, last = _day(min(row.at for row in rows)), _day(max(row.at for row in rows))
+ return last.isoformat() if first == last else f"{first.isoformat()} to {last.isoformat()}"
+
+
def _object_line(
scope: str, activity: str, name: str, rows: Sequence[ActivityItem], context: str, limits: RenderLimits
) -> _ActivityLine:
- latest = max(row.at for row in rows)
count = f" (x{len(rows)})" if len(rows) > 1 else ""
- line = f'- {_day(latest).isoformat()} {activity} {scope} "{_display_name(name)}"{context}{count}'
+ line = f'- {_day_span(rows)} {activity} {scope} "{_display_name(name)}"{context}{count}'
return _activity_line(line, rows, limits, created=activity == "created")
@@ -637,7 +682,6 @@ def _group_line(
) -> _ActivityLine:
"""One line for a parent and the children merged into it, children ranked like lines."""
rows = [row for key in (*own, *children) for row in collapsed[key]]
- latest = max(row.at for row in rows)
ranked_children = sorted(
children,
key=lambda key: (
@@ -656,7 +700,7 @@ def _group_line(
else:
activities = sorted({key[1] for key in children}, key=lambda activity: (activity != "created", activity))
head = f"{' and '.join(activities)} {child_text} on {parent_text}: "
- head = f"- {_day(latest).isoformat()} {head}"
+ head = f"- {_day_span(rows)} {head}"
intent, _ = _intent_text(rows, limits)
suffix_chars = len(f" (agent: {intent})") if intent else 0
line = head + _quoted_names(names, limits.activity_line_chars - len(head) - suffix_chars)
@@ -739,6 +783,13 @@ def is_auto_named(name: str) -> bool:
return _AUTO_NAME.search(name) is not None
+# Every `person_activity` call checks each row, and a window repeats the same names many times.
[email protected]_cache(maxsize=4096)
+def is_unnamed(name: str) -> bool:
+ """True for an empty name, and for a name that is only masks or digits once `clean_text` masks it."""
+ return _MEANINGLESS_NAME.fullmatch(clean_text(name, ACTIVITY_NAME_CHARS * 2)) is not None
+
+
def _has_intent(item: ActivityItem) -> bool:
return bool(item.intent and item.intent.strip())
@@ -756,7 +807,10 @@ def _row_drop(item: ActivityItem) -> Drop | None:
return Drop.API_KEY_ANNOTATION
if item.scope in ONBOARDING_CONFIG_SCOPES and name.startswith(CANONICAL_SCOUT_PREFIX) and not _has_intent(item):
return Drop.ONBOARDING_SCOUT_CONFIG
- if not name:
+ is_setup = item.scope in SETUP_SCOPES or (item.scope == PERSON_SCOPE and item.activity == "deleted")
+ if is_setup and not _has_intent(item):
+ return Drop.SETUP_SCOPE
+ if is_unnamed(name):
return Drop.UNNAMED_OBJECT
if _AUTO_NAME.search(name):
return Drop.AUTO_NAMED_OBJECT
@@ -850,7 +904,7 @@ def _collapse_bulk(
def _drop_team_settings(items: Sequence[ActivityItem], drops: Counter[str]) -> list[ActivityItem]:
"""Without the team settings rows that state no intent, when there are `MIN_TEAM_SETTINGS_ROWS` or more."""
- unstated = [item for item in items if item.scope == TEAM_SCOPE and not _has_intent(item)]
+ unstated = [item for item in items if item.scope in TEAM_SETTINGS_SCOPES and not _has_intent(item)]
if len(unstated) < MIN_TEAM_SETTINGS_ROWS:
return list(items)
drops[Drop.TEAM_SETTINGS] += len(unstated)
@@ -957,17 +1011,30 @@ def without_products(
return kept_activity, kept_views
-def _days(count: int) -> str:
+def days_text(count: int) -> str:
return f"{count} day" if count == 1 else f"{count} days"
+def page_products(views: Iterable[ViewItem], drops: Counter[str]) -> set[Product]:
+ """The products of the opened scenes. The "p" lines of the computed block show them, so they get no view line."""
+ products: set[Product] = set()
+ for view in views:
+ if view.type != SCENE_VIEW_TYPE:
+ continue
+ if (product := scene_product(view.ref)) is None:
+ drops[Drop.GENERIC_SCENE] += 1
+ else:
+ products.add(product)
+ return products
+
+
def view_units(
views: Iterable[ViewItem],
activity: Iterable[ActivityItem],
drops: Counter[str],
limits: RenderLimits = DEFAULT_LIMITS,
) -> list[Unit]:
- """One line per opened object and one per product of the opened scenes, the most opened first.
+ """One line per opened object, the most opened first. Scenes are in `page_products`.
An object line also counts the days the person edited it, matched to their activity rows by
scope and name. These lines skip the per-day burst cap."""
@@ -975,18 +1042,11 @@ def view_units(
for item in person_activity(activity, Counter(), limits)[0]:
edit_days.setdefault((item.scope, (item.name or "").strip()), set()).add(_day(item.at))
ranked: list[tuple[int, datetime.datetime, str]] = []
- scenes: dict[Product, tuple[datetime.datetime, set[datetime.date]]] = {}
for view in views:
if view.type == SCENE_VIEW_TYPE:
- product = scene_product(view.ref)
- if product is None:
- drops[Drop.GENERIC_SCENE] += 1
- continue
- at, days = scenes.get(product, (view.at, set()))
- scenes[product] = (max(at, view.at), days | set(view.days))
continue
name = (view.name or "").strip()
- if not name:
+ if is_unnamed(name):
drops[Drop.UNNAMED_OBJECT] += 1
continue
if _AUTO_NAME.search(name):
@@ -994,21 +1054,13 @@ def view_units(
continue
opened = len(set(view.days))
name_text = cap_line(clean_text(name, ACTIVITY_NAME_CHARS * 2), ACTIVITY_NAME_CHARS)
- facts = [f"opened {_days(opened)}", f"last {_day(view.at).isoformat()}"]
+ facts = [f"opened {days_text(opened)}", f"last {_day(view.at).isoformat()}"]
if edited := len(edit_days.get((scope_of(view.type), name), ())):
- facts.append(f"edited {_days(edited)}")
+ facts.append(f"edited {days_text(edited)}")
if view.not_theirs:
facts.append("not theirs")
label = view.type.split("/")[0].replace("_", " ").capitalize()
ranked.append((opened, view.at, f'- {label} "{name_text}": {", ".join(facts)}'))
- for product, (at, days) in scenes.items():
- ranked.append(
- (
- len(days),
- at,
- f"- {PRODUCT_LABELS[product]} pages: opened {_days(len(days))}, last {_day(at).isoformat()}",
- )
- )
ranked.sort(key=lambda entry: (-entry[0], -entry[1].timestamp(), entry[2]))
if len(ranked) > limits.view_lines:
drops[Drop.SAMPLE_CAP] += len(ranked) - limits.view_lines
@@ -1241,16 +1293,18 @@ def build_input(
person's agent from the MCP intent buffer, and gets its own section after the activity."""
drops: Counter[str] = Counter()
activity = list(activity)
+ views = list(views)
task_pool = burst_cap(dedupe_latest(task_units(tasks, drops, limits), drops), drops, limits.max_units_per_day)
capped_before = drops[Drop.SAMPLE_CAP] + drops[Drop.BURST_CAP]
activity_lines = activity_units(activity, drops, parents, limits)
# Lines that `activity_units` dropped for its line cap or its per-day cap.
activity_pool = len(activity_lines) + drops[Drop.SAMPLE_CAP] + drops[Drop.BURST_CAP] - capped_before
view_lines = view_units(views, activity, drops, limits)
+ pages = page_products(views, drops)
mcp_pool = burst_cap(
dedupe_latest(mcp_units(mcp, activity_lines, drops, limits), drops), drops, limits.max_units_per_day
)
- if not task_pool and not activity_lines and not view_lines and not mcp_pool:
+ if not task_pool and not activity_lines and not view_lines and not mcp_pool and not pages:
return None
chosen_tasks = sample_units(task_pool, limit=limits.task_lines, as_of=as_of, seed=seed)
drops[Drop.SAMPLE_CAP] += len(task_pool) - len(chosen_tasks)
@@ -1284,4 +1338,5 @@ def build_input(
n_mcp_lines=len(sections[2][1]),
mcp_chars=len(rendered[2]),
mcp_pool=len(mcp_pool),
+ n_page_units=len(pages),
)
diff --git a/products/signals/backend/test/test_activity_summary_render.py b/products/signals/backend/test/test_activity_summary_render.py
index 6db987e240fa..84f802a9ab5e 100644
--- a/products/signals/backend/test/test_activity_summary_render.py
+++ b/products/signals/backend/test/test_activity_summary_render.py
@@ -9,7 +9,7 @@ import pytest
from openai import APIConnectionError
from parameterized import parameterized
-from products.signals.backend.activity_summary.computed import compute_fields
+from products.signals.backend.activity_summary.computed import MAX_OWNED, compute_fields
from products.signals.backend.activity_summary.prompt import (
MAX_LABEL_CHARS,
MAX_RECENT_SHIFT_CHARS,
@@ -185,7 +185,7 @@ def test_activity_units_filter_collapse_and_rank_creates_first() -> None:
assert [unit.text for unit in units] == [
'- 2026-10-16 created Dashboard "Growth overview"',
- '- 2026-10-18 updated Notebook "Pricing notes" (x2)',
+ '- 2026-10-17 to 2026-10-18 updated Notebook "Pricing notes" (x2)',
]
assert dict(drops) == {
Drop.NOISY_SCOPE: 1,
@@ -230,11 +230,30 @@ def _bulk(count: int, spacing_days: float, intent: str | None = None) -> list[Ac
{Drop.API_KEY_CHANGE: 1},
),
(
- "an integration with a key-like name is kept",
- [_change("Integration", "created", "CI deploy key")],
- ['- 2026-10-18 created Integration "CI deploy key"'],
+ "a setup change is dropped",
+ [
+ _change("Integration", "created", "Slack"),
+ _change("SignalTeamConfig", "updated", "Inbox settings"),
+ _change("Person", "deleted", "Test user"),
+ ],
+ [],
+ {Drop.SETUP_SCOPE: 3},
+ ),
+ (
+ "a setup change with an intent is kept",
+ [_change("Integration", "created", "Slack", intent="Send alerts to the team channel")],
+ ['- 2026-10-18 created Integration "Slack" (agent: Send alerts to the team channel)'],
{},
),
+ (
+ "an object named only by a token or digits is dropped",
+ [
+ _change("Insight", "created", "12345"),
+ _change("Insight", "created", "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d"),
+ ],
+ [],
+ {Drop.UNNAMED_OBJECT: 2},
+ ),
(
"an annotation written through a personal API key is dropped",
[_change("Annotation", "created", "Deploy v1.4.2", credential_type="personal_api_key")],
@@ -256,6 +275,15 @@ def _bulk(count: int, spacing_days: float, intent: str | None = None) -> list[Ac
[],
{Drop.TEAM_SETTINGS: 2},
),
+ (
+ "repeated project settings updates without an intent are dropped",
+ [
+ _change("Project", "updated", "Default project", days_ago=1),
+ _change("Team", "updated", "Default project", days_ago=2),
+ ],
+ [],
+ {Drop.TEAM_SETTINGS: 2},
+ ),
(
"one team settings update is kept",
[_change("Team", "updated", "Default project")],
@@ -313,7 +341,7 @@ def test_activity_units_drop_automated_activity(
(
"collapsed rows carry their intents newest first",
["Add a breakdown", None, "Split the funnel by plan"],
- '- 2026-10-18 updated Insight "Signup funnel" (x3) (agent: Add a breakdown; Split the funnel by plan)',
+ '- 2026-10-17 to 2026-10-18 updated Insight "Signup funnel" (x3) (agent: Add a breakdown; Split the funnel by plan)',
),
(
"an intent keeps only the host of a link",
@@ -469,7 +497,9 @@ def test_a_group_line_lists_the_names_that_fit_and_marks_the_rest() -> None:
[unit] = activity_units(items, Counter(), parents)
- assert unit.text.startswith('- 2026-10-18 created 12 Insights on Dashboard "Quality review": "Insight number 0')
+ assert unit.text.startswith(
+ '- 2026-10-17 to 2026-10-18 created 12 Insights on Dashboard "Quality review": "Insight number 0'
+ )
assert unit.text.endswith('", …')
assert len(unit.text) <= ACTIVITY_LINE_CHARS
@@ -529,6 +559,21 @@ def test_burst_cap_keeps_the_newest_units_of_a_day() -> None:
("an angle-bracketed slack link", "See <https://example.com/a/b> now", "See [link example.com] now"),
("credentials in a url are gone", "Use https://user:[email protected]/x", "Use [link db.example.com]"),
("token-like string", "Use key phx_9f8e7d6c5b4a3f2e1d0c9b8a7f6e5d4c", "Use key <token>"),
+ ("uuid", "Run 3f2b8c1e-9a4d-4e7f-b6c5-1d2e3f4a5b6c failed", "Run <token> failed"),
+ ("hex hash", "Commit 4e1f9a7c2b8d3e6f0a5c9b1d7e2f8a4c6b3d0e9f", "Commit <token>"),
+ ("sk-style key", "Use sk-live-Zq8xW2vR7tY4uP1oL6kJ3h", "Use <token>"),
+ (
+ "jwt",
+ "Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ0ZXN0dXNlcjEyMyJ9.c2lnbmF0dXJlMTIzNDU2Nzg5",
+ "Bearer <token>.<token>.<token>",
+ ),
+ ("short numeric segments of a key", "Use botx-123456789012-1234567890123456-abcdef", "Use <token>"),
+ ("evenly split key", "Use abcd-1234-efgh-5678-ijkl-9012", "Use <token>"),
+ ("url-safe key with short segments", "Use phx_aB3d-Xy9kQ_w2eRt-Lm8nP_zT4v-Hj6s", "Use <token>"),
+ ("a hyphenated name is kept", "checkout-redesign-test-2026", "checkout-redesign-test-2026"),
+ ("a capitalized name is kept", "Q4-Revenue-Forecast-Review-2026", "Q4-Revenue-Forecast-Review-2026"),
+ ("a snake case name is kept", "activity_summary_mcp_pairs_v2", "activity_summary_mcp_pairs_v2"),
+ ("a name with a quarter is kept", "new-onboarding-flow-q4-2026", "new-onboarding-flow-q4-2026"),
("multiline text folds onto one line", "First line\n\n second\tline ", "First line second line"),
(
"ordinary text is untouched",
@@ -601,6 +646,9 @@ def test_build_input_renders_the_four_sections_in_order() -> None:
assert rendered.input_chars == len(rendered.text)
assert build_input([_task("root cause")], [], as_of=AS_OF, seed=1) is None
assert build_input([], [], as_of=AS_OF, seed=1, views=[_view("scene", "Settings")]) is None
+ pages_only = build_input([], [], as_of=AS_OF, seed=1, views=[_view("scene", "ErrorTracking", days=3)])
+ assert pages_only is not None
+ assert (pages_only.text, pages_only.units) == ("", 1)
def test_mcp_units_assemble_each_session_in_order_and_cap_a_long_chain() -> None:
@@ -708,7 +756,7 @@ def test_mcp_units_drop_rules(
assert dict(drops) == expected_drops
-def test_view_units_name_products_count_edits_and_drop_what_says_nothing() -> None:
+def test_view_units_leave_pages_out_count_edits_and_drop_what_says_nothing() -> None:
drops: Counter[str] = Counter()
views = [
_view("scene", "ErrorTrackingIssue", days=2),
@@ -729,11 +777,10 @@ def test_view_units_name_products_count_edits_and_drop_what_says_nothing() -> No
units = view_units(views, activity, drops)
assert sorted(unit.text for unit in units) == [
- "- Error tracking pages: opened 4 days, last 2026-10-18",
'- Feature flag "new-checkout": opened 2 days, last 2026-10-18, edited 2 days',
'- Insight "Weekly signups": opened 5 days, last 2026-10-18, not theirs',
]
- assert dict(drops) == {Drop.GENERIC_SCENE: 2, Drop.AUTO_NAMED_OBJECT: 1, Drop.UNNAMED_OBJECT: 1}
+ assert dict(drops) == {Drop.AUTO_NAMED_OBJECT: 1, Drop.UNNAMED_OBJECT: 1}
def test_compute_fields_split_owned_watched_and_visited() -> None:
@@ -770,6 +817,15 @@ def test_compute_fields_split_owned_watched_and_visited() -> None:
},
{
"ref": "o2",
+ "type": "dashboard",
+ "id": "9",
+ "name": "Growth overview",
+ "edit_days": 1,
+ "last_at": "2026-10-17",
+ "created": True,
+ },
+ {
+ "ref": "o3",
"type": "insight",
"id": "abc",
"name": "Weekly signups",
@@ -779,7 +835,7 @@ def test_compute_fields_split_owned_watched_and_visited() -> None:
},
*(
{
- "ref": f"o{n + 2}",
+ "ref": f"o{n + 3}",
"type": "ticket",
"id": f"t{n}",
"name": f"Ticket #{n}",
@@ -789,19 +845,10 @@ def test_compute_fields_split_owned_watched_and_visited() -> None:
}
for n in (1, 2, 3)
),
- {
- "ref": "o6",
- "type": "dashboard",
- "id": "9",
- "name": "Growth overview",
- "edit_days": 1,
- "last_at": "2026-10-17",
- "created": True,
- },
],
"watched": [
{
- "ref": "o2",
+ "ref": "o3",
"type": "insight",
"id": "abc",
"name": "Weekly signups",
@@ -819,6 +866,36 @@ def test_compute_fields_split_owned_watched_and_visited() -> None:
}
+def test_compute_fields_cap_one_type_and_merge_objects_with_the_same_name() -> None:
+ insights = [
+ _change("Insight", "created", f"Tile {n}", days_ago=1 - n / 1000, item_id=str(n)) for n in range(MAX_OWNED)
+ ]
+ flags = [_change("FeatureFlag", "updated", f"flag-{n}", days_ago=3, item_id=f"f{n}") for n in range(4)]
+ copies = [
+ _change("Notebook", "updated", "Pricing notes", days_ago=4, item_id="n1"),
+ _change("Notebook", "updated", "pricing notes", days_ago=2, item_id="n2"),
+ ]
+ same_day_copies = [
+ _change("Subscription", "created", "Weekly report", days_ago=1.2, item_id=f"s{n}") for n in range(3)
+ ]
+ dashboard = [_change("Dashboard", "created", "Quality review", days_ago=1.5, item_id="d1")]
+
+ owned = compute_fields([], insights + flags + copies + same_day_copies + dashboard, []).as_json()["owned"]
+
+ assert len(owned) == MAX_OWNED
+ assert [(item["type"], item["id"], item["edit_days"]) for item in owned[:2]] == [
+ ("notebook", "n2", 1),
+ ("dashboard", "d1", 1),
+ ]
+ assert Counter(item["type"] for item in owned) == {
+ "insight": MAX_OWNED - 7,
+ "feature_flag": 4,
+ "notebook": 1,
+ "subscription": 1,
+ "dashboard": 1,
+ }
+
+
@parameterized.expand(
[
("default limits", DEFAULT_LIMITS),
@@ -878,7 +955,7 @@ PREVIOUS = {
"modes": ["building"],
"recent_shift": "Moved from flags to funnels.",
}
-COMPUTED = {
+COMPUTED: dict[str, Any] = {
"schema_version": 1,
"owned": [
{
@@ -932,12 +1009,23 @@ def test_user_message_sends_only_the_rendered_input_and_the_previous_summary(
def test_user_message_lists_the_computed_objects_and_pages_with_their_refs() -> None:
- message = user_message("- a line", None, datetime.date(2026, 10, 18), computed=COMPUTED)
+ visits = [f"product_{n}_with_a_long_key" for n in range(8)]
+ computed = COMPUTED | {
+ "owned": [*COMPUTED["owned"], {**COMPUTED["owned"][0], "ref": "o3", "name": "Churn", "edit_days": 1}],
+ "watched": [
+ *COMPUTED["watched"],
+ {**COMPUTED["watched"][0], "ref": "o1", "name": "Signup funnel", "open_days": 9, "last_at": "2026-10-18"},
+ ],
+ "pages": [*COMPUTED["pages"], {"ref": "p2", "product": "surveys", "open_days": 1, "last_at": "2026-10-18"}],
+ "products": {"works_in": ["product_analytics"], "visits": ["session_replay", *visits]},
+ }
+ message = user_message("- a line", None, datetime.date(2026, 10, 18), computed=computed)
assert (
"Objects and pages:\n"
"Products they work in: Product analytics\n"
- "Products they only visit: Session replay\n"
- '- o1 insight "Signup funnel": edited on 3 days, last 2026-10-16, created\n'
+ f"Products they only visit: Session replay, {', '.join(visits)}\n"
+ '- o1 insight "Signup funnel": edited on 3 days, opened on 9 days, last 2026-10-18, created\n'
+ '- o3 insight "Churn": edited on 1 day, last 2026-10-16, created\n'
'- o2 dashboard "Growth overview": opened on 4 days, last 2026-10-17, not theirs\n'
"- p1 Session replay pages: opened on 2 days, last 2026-10-18\n\n"
) in message
diff --git a/products/signals/backend/test/test_activity_summary_tick.py b/products/signals/backend/test/test_activity_summary_tick.py
index 17431f73cd15..37ff9d7f71aa 100644
--- a/products/signals/backend/test/test_activity_summary_tick.py
+++ b/products/signals/backend/test/test_activity_summary_tick.py
@@ -265,13 +265,22 @@ class TestActivitySummaryQueue(BaseTest):
def _user(self, email: str) -> User:
return User.objects.create_and_join(self.organization, email, None)
- def _changes(self, user: User, count: int, *, days_ago: float = 1, team: Team | None = None, **fields: Any):
+ def _changes(
+ self,
+ user: User,
+ count: int,
+ *,
+ days_ago: float = 1,
+ team: Team | None = None,
+ scope: str = "Insight",
+ **fields: Any,
+ ):
for index in range(count):
ActivityLog.objects.create(
team_id=(team or self.team).id,
organization_id=self.organization.id,
user=user,
- scope="Insight",
+ scope=scope,
activity="created",
item_id=str(index),
detail={"name": f"Funnel {index}"},
@@ -397,13 +406,14 @@ class TestActivitySummaryQueue(BaseTest):
]
def test_leaves_out_pairs_that_are_not_due_or_not_enrolled(self) -> None:
- waiting, scout_only, impersonated, skipped_team = (
- self._user(f"{name}@example.com") for name in ("waiting", "scout", "impersonated", "skipped")
+ waiting, scout_only, setup_only, impersonated, skipped_team = (
+ self._user(f"{name}@example.com") for name in ("waiting", "scout", "setup", "impersonated", "skipped")
)
due = self._user("[email protected]")
self._summary(waiting, next_eligible_at=NOW + datetime.timedelta(hours=1))
self._changes(waiting, 3)
self._changes(scout_only, 3, client="scout:product-analytics")
+ self._changes(setup_only, 3, scope="Integration")
self._changes(impersonated, 3, was_impersonated=True)
other_team = Team.objects.create(organization=self.organization, name="Skipped")
self._changes(skipped_team, 3, team=other_team)
diff --git a/products/signals/backend/test/test_activity_summary_update.py b/products/signals/backend/test/test_activity_summary_update.py
index 4732038f4a4e..f84901d80ede 100644
--- a/products/signals/backend/test/test_activity_summary_update.py
+++ b/products/signals/backend/test/test_activity_summary_update.py
@@ -150,10 +150,10 @@ class TestUpdateActivitySummary(BaseTest):
assert result.rendered_input is not None
assert '- Insight "Weekly signups": opened 1 day, last 2026-10-17, not theirs' in result.rendered_input
assert '- Insight "Churn by plan": opened 1 day, last 2026-10-18\n' in result.rendered_input
- assert "- Experiments pages: opened 1 day, last 2026-10-18" in result.rendered_input
+ assert "Experiments pages" not in result.rendered_input
stored = self._stored()
assert stored is not None
- assert stored.inputs_used["view_lines"] == 3
+ assert (stored.inputs_used["view_lines"], stored.inputs_used["page_units"]) == (2, 1)
assert stored.inputs_used["drops"] == {"generic_scene": 1}
assert stored.input_watermark == NOW - datetime.timedelta(days=0.5)