: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(signals): show merged prs and participation in the inbox (#111094)
Dylan Martine08dbbf629b2
diff --git a/docs/internal/signals-pr-lifecycle.md b/docs/internal/signals-pr-lifecycle.mdindex 59c7f25bbd90..130667888817 100644--- a/docs/internal/signals-pr-lifecycle.md+++ b/docs/internal/signals-pr-lifecycle.md@@ -55,6 +55,27 @@ Custom HogQL aggregations are parsed before a metric or check is authored. InvalProtected research runs require analytics access before a person can resume or warm a successor. The successor’s bound sandbox can read the verified source history through authenticated log routes, but cannot modify the source run.+## Inbox value summary++The `signals-inbox-value-summary` flag shows project-wide counts above the web+inbox in both layouts. It is disabled by default. The rolling seven-day window+uses GitHub merge time and includes only PRs verified as output from Self-driving+implementation tasks. Manual attachments and research or discussion tasks do not+count. Personal inbox filters do not change the totals.++The people count deduplicates human GitHub IDs across mergers and non-dismissed+approvals submitted before merge. Approvals can predate the seven-day window.+Bots do not count. A missing participant snapshot leaves the people count unknown,+not zero. The response includes the merged PR links and the GitHub logins stored in+the participant snapshot. GitHub reads run in a background task; opening the inbox+only reads the database.++The panel stays hidden when there are no qualifying merges. Dismissal lasts seven+days and is stored per user and project in that browser. On return, the client+refreshes a result older than five minutes. Before rollout, apply the migrations,+run `backfill_inbox_summary --team-id <id>` in bounded batches, and check the counts+against the linked GitHub PRs. The flag does not enable this backfill itself.+## Follow-up measurement timingReopening or archiving a resolved report immediately parks its active checks and clears their measurement starts and dispatches. It resets both error and inconclusive retry streaks. Delayed resolution callbacks only arm checks while the report is still resolved. Results from an earlier measurement window or dispatch cannot update the current check.diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 3f30d035822e..a64da8efdde1 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -11466,6 +11466,10 @@ snapshots:hash: v1.k794b7964.aef8677fa43f11ff5f5b34c381208ef202da80771a5d2d17281d2a98d3361604.f8rgo5YeHpzk4rc50ylbjLdcTDBYNGJPqO--MNXk1Fwscenes-app-inbox-scene--legacy-scouts--light:hash: v1.k794b7964.9dd3dc8e6e80c8b05907082af42a22344b194f047b52fb748b67b7f801e95f5f.Z_d39bmfXBtFI0yeryorC9eA0mg0Uhgc01sSEDLa_vk+ scenes-app-inbox-scene--legacy-with-value-summary--dark:+ hash: v1.k794b7964.20ee6fce51c55f6dd8ee42bdb43e5be2e99f8a7eabaeb8a966b65975b3ce114b.PPjKVc4DfAnR46COWDLiAmarWSC0W4hpvQsMYoUstQg+ scenes-app-inbox-scene--legacy-with-value-summary--light:+ hash: v1.k794b7964.9a60fdda0fcf25cc34965bfedddadf9c4d4d9522c478f6b0fc8a4dcacf5ff886.JE0icmhQT3FrnbbeB2GJ4HiqsYOA_NkeSFzVR7apeLQscenes-app-inbox-scene--report-with-many-evidence-items--dark:hash: v1.k794b7964.cdf433915e692e878772c4299885f968c99c039e535ce00eedde96142225dc8a.3jz4_ynFjRQTKIFVz6-5ofn0AVAdDN3pilwzZWHmrKoscenes-app-inbox-scene--report-with-many-evidence-items--light:@@ -11502,6 +11506,10 @@ snapshots:hash: v1.k794b7964.77e43b36fdcd81befecf4de80e489050f525840924ec6ddef37c23a9179dbe8a.B3qkZFYBncFaPn2EBg4cBoYu_LIwW29imNwBdLXF5eoscenes-app-inbox-scene--triage--light:hash: v1.k794b7964.ea1f0a1a3cd9c029a33e39277a276be15a04555ba2addee17df2aacb108316dc.CFYN_7EjRWTlSCsBQMuZ6Bq_ViTyRy7_RqqtqKfg05w+ scenes-app-inbox-scene--with-value-summary--dark:+ hash: v1.k794b7964.da442cf38ae973d71a93a7c3693e4a4be7540d887d722cb17488f721ae600a62.eWp2_J6KUorzw1uhRM5J9veF0F0cb5OQJI2MXU5ZZh8+ scenes-app-inbox-scene--with-value-summary--light:+ hash: v1.k794b7964.81bdb7acaef7db28d14a2d1df79e654eddfc2455c8cab58e000ee7ff14fe9a08.nNE7Sqvdo1LmUS7wWifL9Jpynqax76-wUUhqGwQKZpkscenes-app-inbox-scout-comparison-report--completed--dark:hash: v1.k794b7964.179dd1ea74dfa1727c501df365f491d5bb9246bfc731ac4821594687795197b1.Za7jkz_YuKW0eyjzp928-Hv652aROII5i6Da4dNfiukscenes-app-inbox-scout-comparison-report--completed--light:@@ -12218,6 +12226,34 @@ snapshots:hash: v1.k794b7964.f08e33da24a85604e6c034e0e75ea9aee591e95a89bd7f641d8e7fd14d035cba.jvSH7jzc9QVJhYUhHnmPZSZ6R4YZ3bIlaGEvQAGK5rAscenes-app-inbox-usagewidget--within-free-tier--light:hash: v1.k794b7964.648bee645e8d97ed41b88b2f64ad75bbb9d0e54f6bf5395483e6f69717a80dc9.lU5ww7_KZ4Zxgkg2mtj0PyFXeH_CCdGCUyWkUD0q7AQ+ scenes-app-inbox-valuesummary--complete--dark:+ hash: v1.k794b7964.fad6a3d2a448f5cde95c0075d7557f95735e5bb4cefb9584e740edf426a2d027.1IhRfMqjXy_sRLvPoB-GJr2aza7WDFNKyR3OcKI0J5M+ scenes-app-inbox-valuesummary--complete--light:+ hash: v1.k794b7964.410a1e9ef73e51d3a5d929a56c630d8a045afe5bbb3ed060fceacfecf32b4ac9.dLZaeGH6DlZHeC6BFuOGfcyhF2nrpfGqPiMrYVFpCmQ+ scenes-app-inbox-valuesummary--error--dark:+ hash: v1.k794b7964.9a57d1cb852d4a201a6d35e68490822c1b22edcb0fd4af4854093db47494f6fe.YT4g5i41Y8eqjmLVsstpdGkBVZvz9CywsFsUcHUyuG0+ scenes-app-inbox-valuesummary--error--light:+ hash: v1.k794b7964.9ccf1c833aa83e8a985956e355540a08c49a009a627810c373980258dac396a2.xIOdqR2eHniNpuVP0N23xG_QjDxzp-iJ77XHxOLCcVE+ scenes-app-inbox-valuesummary--narrow--dark:+ hash: v1.k794b7964.03c507cd5148a25f9f904ac355c7031d964198a24760557cdfe0e25c3c507c43.lzJSfTJzIM_3QXxe23fTgNNJ8joul-7ZyH0fNZ0GQLY+ scenes-app-inbox-valuesummary--narrow--light:+ hash: v1.k794b7964.a5fe4fc7f47cf8af80c0167ea93f430d00fbbee16410d639d08c4c1052ab91d2.4C_PdtL2dUoXtJ0QDgneLaQPvuYL6GuC6Acaj3_yYTo+ scenes-app-inbox-valuesummary--no-merges--dark:+ hash: v1.k794b7964.5114bd6770b3f496dd3fdfa1537a3d00a05703d08afc2c16259015d402762346.4nZRBW6JQt0ImnX7jjb-_VAFigHxltWt9yJtF485tzI+ scenes-app-inbox-valuesummary--no-merges--light:+ hash: v1.k794b7964.1de246fb2561004dbe984e83bc79b290f83ffcb97a95c3f1956ad58814727efe.YR58CMd58r-BGYmeRo8IHf1KIQNMwfhq45yE5PwLzJo+ scenes-app-inbox-valuesummary--people-open--dark:+ hash: v1.k794b7964.7d593e1cc8b6c8fe8fff080ed3575add255174ccb493e7ef44bb4e7c7f23a5ff.JbI5aZCTlLGYuvx6RJeF-ixZhS9jColNJZlyEuEb9Tg+ scenes-app-inbox-valuesummary--people-open--light:+ hash: v1.k794b7964.a048b366583e4f785e921e00aac9361b66c37bc5121b4993933fc78ee1534fb6.Puk5c3xZTKTdd8V6QjQOP0LjCUaG0PfKXXjRuVGzwqc+ scenes-app-inbox-valuesummary--pull-requests-open--dark:+ hash: v1.k794b7964.b14143a300b61ef0d82e0dabd29ba4c24372bf26fe243c2b55a1f196a833afba.4rMemJGW5wITkxXpliX5DPOrkO0qMsGwORrP2eKOwng+ scenes-app-inbox-valuesummary--pull-requests-open--light:+ hash: v1.k794b7964.cab26b2e23cc524ad9d767314380d8800653f2215ff6d9362d25d27e02cd25ce.Upv00UvfLQ1DGuv4rsf1pDdPmIRa_qxPm2goiZpuzCw+ scenes-app-inbox-valuesummary--updating-people--dark:+ hash: v1.k794b7964.af4a19c64fe743b316170687a91ce71c62fb631dca0e66e818a97ffbd76fb18f.8uWV7I_RwC9uB3q1MeSW3mehNXuwYbZUnFyFYXPnSiI+ scenes-app-inbox-valuesummary--updating-people--light:+ hash: v1.k794b7964.8912f3bbb0dfa2938f8a8dc71a11d7189bf7f234d89e2d27710595e364eb7fae.Qnn6S8QP3rgpV9NyieP28BZZoW-hkNauQ6drneNp5XAscenes-app-insights-error-empty-states--empty--dark:hash: v1.k794b7964.3961b0ca114d960fbca2a03aacb411a4153f810cf590a791dd8b780473b99ba9.zRgVF3H2u30h4drwmVvPbj77AdUT3XFPc2IooRyV0Osscenes-app-insights-error-empty-states--empty--light:diff --git a/frontend/src/initKea.ts b/frontend/src/initKea.tsindex d561bf143a2c..62af0e543fab 100644--- a/frontend/src/initKea.ts+++ b/frontend/src/initKea.ts@@ -29,6 +29,7 @@ const ERROR_FILTER_ALLOW_LIST = ['fetchLogs', // Logs and tracing show a warning icon on the pane whose query failed.'fetchSpans','fetchSparkline',+ 'loadInboxSummary', // The inbox summary has an inline retry control.'loadOfflineExperiments', // Offline views provide inline retry states.'loadOfflineScorerOptions','loadOfflineSuggestedScorers',diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex cc20e968e2d7..c99f1d54e0ae 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -256,6 +256,7 @@ export const FEATURE_FLAGS = {SETTINGS_SESSIONS_V2_JOIN: 'settings-sessions-v2-join', // owner: @robbie-c #team-web-analyticsSETTINGS_WEB_ANALYTICS_PRE_AGGREGATED_TABLES: 'web-analytics-pre-aggregated-tables', // owner: @lricoy #team-web-analyticsSIGNALS_EXPECTED_IMPACT_DISPLAY: 'signals-expected-impact', // owner: #team-self-driving, person-level display gate for metric follow-up graphs and actions+ SIGNALS_INBOX_VALUE_SUMMARY: 'signals-inbox-value-summary', // owner: #team-self-drivingSIGNALS_PR_REFUNDS: 'signals-pr-refunds', // owner: #team-self-driving, gates the inbox PR refund flow (also checked server-side)SIGNALS_REPORT_CHECKS_REPLACE: 'signals-report-checks-replace', // owner: #team-self-drivingSIGNALS_REPORT_METRICS: 'signals-report-metrics', // owner: #team-self-driving, gates the live impact metrics on inbox report rows and the report detail, and the snapshot refresh calls they makediff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.pyindex d29caf833a97..ee3cda0fe8d2 100644--- a/posthog/models/github_integration_base.py+++ b/posthog/models/github_integration_base.py@@ -877,11 +877,20 @@ class GitHubIntegrationBase:logger.warning("GitHubIntegration: installation POST failed", url=url, exc_info=True)return None- def installation_can_access_repository(self, repository: str) -> bool:+ def installation_can_access_repository(self, repository: str, *, raise_on_transient: bool = False) -> bool:"""Whether this installation token can access the repo (``GET /repos/{owner}/{repo}`` returns 200)."""- response = self._installation_authenticated_get(- f"https://api.github.com/repos/{repository}", endpoint="/repos/{owner}/{repo}"- )+ url = f"https://api.github.com/repos/{repository}"+ response: requests.Response | None+ if raise_on_transient:+ response = self.api_request(+ "GET", url.removeprefix("https://api.github.com"), endpoint="/repos/{owner}/{repo}"+ )+ if response.status_code >= 500:+ raise GitHubIntegrationError(+ "GitHub repository access probe failed transiently", status_code=response.status_code+ )+ else:+ response = self._installation_authenticated_get(url, endpoint="/repos/{owner}/{repo}")if response is None:return Falsereturn response.status_code == 200@@ -1239,6 +1248,7 @@ class GitHubIntegrationBase:"created_at": pr.get("created_at"),"updated_at": pr.get("updated_at"),"merged_at": pr.get("merged_at"),+ "merged_by": pr.get("merged_by"),"closed_at": pr.get("closed_at"),"comments": pr.get("comments", 0),"review_comments": pr.get("review_comments", 0),@@ -1248,6 +1258,27 @@ class GitHubIntegrationBase:"changed_files": pr.get("changed_files", 0),}+ def get_pull_request_reviews(self, repository: str, pr_number: int) -> list[dict[str, Any]]:+ if not _is_safe_github_repo_path(repository) or type(pr_number) is not int or pr_number <= 0:+ raise GitHubIntegrationError("Invalid pull request identity")+ responses, complete = self._installation_authenticated_get_pages(+ f"https://api.github.com/repos/{repository}/pulls/{pr_number}/reviews",+ endpoint="/repos/{owner}/{repo}/pulls/{pull_number}/reviews",+ params={"per_page": 100},+ )+ if not complete:+ raise GitHubIntegrationError("Could not fetch all pull request reviews")+ reviews: list[dict[str, Any]] = []+ for response in responses:+ try:+ page = response.json()+ except ValueError as error:+ raise GitHubIntegrationError("Could not parse pull request reviews") from error+ if not isinstance(page, list) or any(not isinstance(review, dict) for review in page):+ raise GitHubIntegrationError("Invalid pull request reviews")+ reviews.extend(page)+ return reviews+def get_pull_request_from_url(self, pr_url: str) -> dict[str, Any]:"""Fetch a pull request by its HTML URL (e.g. ``https://github.com/owner/repo/pull/123``)."""parsed = self.parse_pull_request_url(pr_url)diff --git a/posthog/models/integration/github.py b/posthog/models/integration/github.pyindex e65ad8a38061..b922b2c0bfff 100644--- a/posthog/models/integration/github.py+++ b/posthog/models/integration/github.py@@ -344,8 +344,9 @@ class GitHubIntegration(GitHubIntegrationBase):that isn't a plain ``owner/repo`` first, so a crafted value (``owner/repo/contents/x?ref=y``)can't steer that authenticated request to a different GitHub endpoint as a probe.- An installation whose probe runs out of egress budget or hits GitHub's rate limit is- skipped. When no other installation covers the repository, that first error is raised.+ An installation whose probe fails transiently, runs out of egress budget, or hits GitHub's+ rate limit is skipped. When no other installation covers the repository, that first error+ is raised."""if not _is_safe_github_repo_path(repository):return None@@ -353,8 +354,8 @@ class GitHubIntegration(GitHubIntegrationBase):for integration in model.Integration.objects.filter(team_id=team_id, kind="github").order_by("id"):github = cls(integration, source=source, priority=priority)try:- covers = github.installation_can_access_repository(repository)- except (EgressBudgetExhausted, GitHubRateLimitError) as e:+ covers = github.installation_can_access_repository(repository, raise_on_transient=True)+ except (EgressBudgetExhausted, GitHubRateLimitError, GitHubIntegrationError) as e:# A team's first installation being out of budget must not hide a later one that# covers the repository. The first error is kept and raised only when none does,# so a caller that has no reader still sees why.diff --git a/posthog/models/test/integration/test_github.py b/posthog/models/test/integration/test_github.pyindex d6f6ff40073e..1202c7327520 100644--- a/posthog/models/test/integration/test_github.py+++ b/posthog/models/test/integration/test_github.py@@ -949,12 +949,19 @@ class TestGitHubIntegrationModel(BaseTest):self.team.id, "PostHog/posthog", source="test", priority=Priority.CRITICAL)assert result is not None- mock_access.assert_called_once_with("PostHog/posthog")+ mock_access.assert_called_once_with("PostHog/posthog", raise_on_transient=True)++ def test_repository_access_probe_raises_after_transient_retries_are_exhausted(self):+ github = GitHubIntegration(MagicMock(kind="github"), source="test", priority=Priority.CRITICAL)+ with patch.object(github, "api_request", return_value=MagicMock(status_code=503)):+ with pytest.raises(GitHubIntegrationError, match="failed transiently"):+ github.installation_can_access_repository("PostHog/posthog", raise_on_transient=True)@parameterized.expand([("our_budget", GitHubEgressBudgetExhausted("shed")),("githubs_limit", GitHubRateLimitError("429")),+ ("transient_failure", GitHubIntegrationError("unavailable", status_code=503)),])def test_first_for_team_repository_looks_past_an_exhausted_installation(self, _name, error):@@ -973,6 +980,7 @@ class TestGitHubIntegrationModel(BaseTest):[("our_budget", GitHubEgressBudgetExhausted("shed")),("githubs_limit", GitHubRateLimitError("429")),+ ("transient_failure", GitHubIntegrationError("unavailable", status_code=503)),])def test_first_for_team_repository_raises_when_only_an_exhausted_installation_could_have_covered(diff --git a/posthog/test/repo_invariants/test_pagination_contract.py b/posthog/test/repo_invariants/test_pagination_contract.pyindex 06440d4bc118..afe498475c20 100644--- a/posthog/test/repo_invariants/test_pagination_contract.py+++ b/posthog/test/repo_invariants/test_pagination_contract.py@@ -219,6 +219,8 @@ EXISTING_CUSTOM_LIST_VIEWSETS = {"products.review_hog.backend.presentation.views.resolution.ReviewResolutionConfigViewSet","products.review_hog.backend.presentation.views.reviews.ReviewRecentReviewsViewSet","products.review_hog.backend.presentation.views.validators.ReviewValidatorConfigViewSet",+ # Counts and hover details must use the same complete seven-day window.+ "products.signals.backend.presentation.inbox_summary.InboxSummaryViewSet","products.signals.backend.scout_harness.views.SignalScoutConfigViewSet","products.signals.backend.scout_harness.views.SignalScoutMembersViewSet","products.signals.backend.scout_harness.views.SignalScoutNoteViewSet",diff --git a/products/signals/backend/facade/api.py b/products/signals/backend/facade/api.pyindex a696b399082f..c1c790ca1220 100644--- a/products/signals/backend/facade/api.py+++ b/products/signals/backend/facade/api.py@@ -8,6 +8,8 @@ from typing import TYPE_CHECKING, Anyfrom django.conf import settingsfrom django.db import transaction+from django.db.models import Q+from django.utils import timezoneimport pydanticimport structlog@@ -46,7 +48,17 @@ from products.signals.backend.briefing_reports import ()from products.signals.backend.contracts import DIRECT_STEERABLE_SOURCES, SIGNAL_VARIANT_LOOKUP, SignalRemediationfrom products.signals.backend.enums import SIGNAL_SOURCE_PRODUCT_LABELS, SignalSourceProduct-from products.signals.backend.models import SignalReport, SignalScoutConfig, SignalScoutRun, SignalSourceConfig+from products.signals.backend.inbox_summary import (+ INBOX_SUMMARY_PERIOD as INBOX_SUMMARY_PERIOD,+ generated_pull_requests,+)+from products.signals.backend.models import (+ SignalReport,+ SignalReportPullRequest,+ SignalScoutConfig,+ SignalScoutRun,+ SignalSourceConfig,+)from products.signals.backend.report_access import may_read_reports as may_read_reportsfrom products.signals.backend.report_actionability_repair import RepairedBatch, repair_latest_actionabilityfrom products.signals.backend.report_metric_access import (@@ -93,6 +105,7 @@ from products.signals.backend.signal_metadata import SourceSliceSignalStats, fet# Re-exported for external products (tasks presentation catches it around facade create_task).from products.signals.backend.task_run_artefacts import ReportTaskCapExceeded as ReportTaskCapExceeded+from products.tasks.backend.facade import api as tasks_facadefrom products.tasks.backend.facade.access import is_sandbox_run_requestif TYPE_CHECKING:@@ -104,6 +117,92 @@ MAX_SIGNAL_DESCRIPTION_TOKENS = 8000MAX_SIGNAL_REMEDIATION_TOKENS = 16000+@frozen+class InboxSummaryPullRequest:+ repository: str+ number: int+ url: str+++@frozen+class InboxSummaryPerson:+ id: int+ login: str+++@frozen+class InboxSummary:+ period_start: datetime+ period_end: datetime+ merged_pr_count: int+ people_count: int | None+ participation_complete: bool+ pull_requests: tuple[InboxSummaryPullRequest, ...]+ people: tuple[InboxSummaryPerson, ...] | None+++def get_inbox_summary(*, team_id: int, user: object | None = None, service_auth: bool = False) -> InboxSummary:+ if service_auth:+ rows = generated_pull_requests(team_id)+ elif isinstance(user, User):+ access = tasks_facade.task_access_scope(team_id=team_id, user=user)+ task_filter = tasks_facade.visible_tasks_q(access.user_id, relation="task")+ if not access.has_resource_access:+ task_filter &= Q(task_id__in=access.allowed_ids) | Q(task__created_by_id=access.user_id)+ elif access.blocked_ids:+ task_filter &= ~(Q(task_id__in=access.blocked_ids) & ~Q(task__created_by_id=access.user_id))+ rows = generated_pull_requests(team_id, task_filter=task_filter)+ else:+ rows = SignalReportPullRequest.objects.for_team(team_id).none()++ period_end = timezone.now()+ period_start = period_end - INBOX_SUMMARY_PERIOD+ merged_rows = (+ rows.filter(state="merged", merged_at__gte=period_start, merged_at__lt=period_end)+ .values(+ "number",+ "participant_ids",+ "participant_logins",+ "participants_synced_at",+ "repository",+ "url",+ )+ .order_by("-merged_at", "repository", "number")+ )+ participation_complete = True+ people_by_id: dict[int, str] = {}+ pull_requests: list[InboxSummaryPullRequest] = []+ for row in merged_rows.iterator():+ pull_requests.append(+ InboxSummaryPullRequest(repository=row["repository"], number=row["number"], url=row["url"])+ )+ participant_ids = row["participant_ids"]+ participant_logins = row["participant_logins"]+ if (+ participant_ids is None+ or participant_logins is None+ or row["participants_synced_at"] is None+ or len(participant_ids) != len(participant_logins)+ ):+ participation_complete = False+ else:+ for participant_id, login in zip(participant_ids, participant_logins, strict=True):+ people_by_id.setdefault(participant_id, login)+ people = tuple(+ InboxSummaryPerson(id=participant_id, login=login)+ for participant_id, login in sorted(people_by_id.items(), key=lambda item: (item[1].lower(), item[0]))+ )+ return InboxSummary(+ period_start=period_start,+ period_end=period_end,+ merged_pr_count=len(pull_requests),+ people_count=len(people) if participation_complete else None,+ participation_complete=participation_complete,+ pull_requests=tuple(pull_requests),+ people=people if participation_complete else None,+ )++@frozenclass ScoutTrialSkill:name: strdiff --git a/products/signals/backend/inbox_summary.py b/products/signals/backend/inbox_summary.pynew file mode 100644index 000000000000..b496dce9dd24--- /dev/null+++ b/products/signals/backend/inbox_summary.py@@ -0,0 +1,184 @@+from datetime import datetime, timedelta++from django.db.models import Exists, OuterRef, Q, QuerySet, TextField, Value+from django.db.models.functions import Cast, Concat, JSONArray+from django.utils import timezone+from django.utils.dateparse import parse_datetime++from posthog.dataclasses import frozen+from posthog.egress.github.transport import GitHubEgressBudgetExhausted, GitHubRateLimitError+from posthog.egress.limiter.policies import Priority+from posthog.models.github_integration_base import GitHubIntegrationBase, GitHubIntegrationError+from posthog.models.integration import GitHubIntegration+from posthog.models.organization import OrganizationMembership+from posthog.models.user_integration import UserGitHubIntegration++from products.signals.backend.artefact_schemas import TASK_RUN_TYPE_IMPLEMENTATION+from products.signals.backend.models import SignalReportPullRequest, SignalReportTask++INBOX_SUMMARY_PERIOD = timedelta(days=7)+++@frozen+class GitHubParticipant:+ id: int+ login: str+++def generated_pull_requests(team_id: int, *, task_filter: Q | None = None) -> QuerySet[SignalReportPullRequest]:+ # Neither a manually attached PR nor an API-writable task output proves that the task created it.+ implementations = SignalReportTask.objects.filter(+ team_id=team_id,+ relationship=TASK_RUN_TYPE_IMPLEMENTATION,+ task__team_id=team_id,+ task__runs__team_id=team_id,+ ).filter(+ Q(task__runs__state__verified_pr_urls__contains=JSONArray(OuterRef("url")))+ | Q(+ task__runs__state__verified_pr_urls__contains=JSONArray(+ Concat(+ Value("https://github.com/"),+ OuterRef("repository"),+ Value("/pull/"),+ Cast(OuterRef("number"), TextField()),+ output_field=TextField(),+ )+ )+ )+ )+ if task_filter is not None:+ implementations = implementations.filter(task_filter)+ return SignalReportPullRequest.objects.for_team(team_id).filter(Exists(implementations))+++def github_datetime(value: object) -> datetime | None:+ if not isinstance(value, str):+ return None+ try:+ parsed = parse_datetime(value)+ except ValueError:+ return None+ return parsed if parsed is not None and timezone.is_aware(parsed) else None+++def human_participant(user: object) -> GitHubParticipant | None:+ if not isinstance(user, dict):+ raise GitHubIntegrationError("Missing pull request participant")+ login = user.get("login")+ if user.get("type") == "Bot" or (isinstance(login, str) and login.lower().endswith("[bot]")):+ return None+ user_id = user["id"]+ if (+ user.get("type") != "User"+ or type(user_id) is not int+ or user_id <= 0+ or not isinstance(login, str)+ or not login+ or len(login) > 255+ ):+ raise GitHubIntegrationError("Unknown pull request participant")+ return GitHubParticipant(id=user_id, login=login)+++def github_for_generated_pull_request(+ *, team_id: int, repository: str, pr_number: int, pr_url: str+) -> GitHubIntegrationBase | None:+ verified_url = f"https://github.com/{repository.lower()}/pull/{pr_number}"+ implementations = (+ SignalReportTask.objects.filter(+ team_id=team_id,+ relationship=TASK_RUN_TYPE_IMPLEMENTATION,+ task__team_id=team_id,+ task__runs__team_id=team_id,+ )+ .filter(+ Q(task__runs__state__verified_pr_urls__contains=[verified_url])+ | Q(task__runs__state__verified_pr_urls__contains=[pr_url])+ )+ .select_related("task__github_integration", "task__github_user_integration", "task__team")+ .order_by("task_id")+ )+ seen_task_ids: set[str] = set()+ probe_error: Exception | None = None+ for implementation in implementations.iterator():+ task = implementation.task+ task_id = str(task.id)+ if task_id in seen_task_ids:+ continue+ seen_task_ids.add(task_id)+ personal = task.github_user_integration+ if (+ personal is not None+ and personal.kind == "github"+ and personal.user_id == task.created_by_id+ and OrganizationMembership.objects.filter(+ user_id=personal.user_id, organization_id=task.team.organization_id+ ).exists()+ ):+ personal_github = UserGitHubIntegration(personal, source="signals_inbox_summary", priority=Priority.BATCH)+ try:+ if personal_github.installation_can_access_repository(repository, raise_on_transient=True):+ return personal_github+ except (GitHubEgressBudgetExhausted, GitHubRateLimitError, GitHubIntegrationError) as error:+ probe_error = probe_error or error+ integration = task.github_integration+ if integration is not None and integration.kind == "github" and integration.team_id == team_id:+ team_github = GitHubIntegration(integration, source="signals_inbox_summary", priority=Priority.BATCH)+ try:+ if team_github.installation_can_access_repository(repository, raise_on_transient=True):+ return team_github+ except (GitHubEgressBudgetExhausted, GitHubRateLimitError, GitHubIntegrationError) as error:+ probe_error = probe_error or error+ fallback = GitHubIntegration.first_for_team_repository(+ team_id, repository, source="signals_inbox_summary", priority=Priority.BATCH+ )+ if fallback is not None:+ return fallback+ if probe_error is not None:+ raise probe_error+ return None+++def sync_pull_request_participants(*, team_id: int, repository: str, pr_number: int) -> None:+ pr = (+ generated_pull_requests(team_id).filter(repository=repository.lower(), number=pr_number, state="merged").first()+ )+ if pr is None:+ return+ github = github_for_generated_pull_request(+ team_id=team_id, repository=pr.repository, pr_number=pr.number, pr_url=pr.url+ )+ if github is None:+ return+ snapshot = github.get_pull_request(pr.repository, pr.number)+ if not snapshot.get("success"):+ raise GitHubIntegrationError("Could not fetch merged pull request")+ merged_at = github_datetime(snapshot["merged_at"])+ if snapshot.get("merged") is not True or merged_at is None:+ raise GitHubIntegrationError("Missing verified merge time")+ now = timezone.now()+ SignalReportPullRequest.objects.for_team(team_id).filter(id=pr.id).update(merged_at=merged_at, checked_at=now)+ # Repair the merge time before applying the window: older imports can have no timestamp.+ if merged_at < now - INBOX_SUMMARY_PERIOD:+ return+ participants: dict[int, str] = {}+ merger = human_participant(snapshot["merged_by"])+ if merger is not None:+ participants[merger.id] = merger.login+ for review in github.get_pull_request_reviews(pr.repository, pr.number):+ if review.get("state") != "APPROVED":+ continue+ submitted_at = github_datetime(review.get("submitted_at"))+ if submitted_at is None:+ raise GitHubIntegrationError("Missing approval time")+ if submitted_at <= merged_at:+ reviewer = human_participant(review.get("user"))+ if reviewer is not None:+ participants[reviewer.id] = reviewer.login+ participant_ids = sorted(participants)+ SignalReportPullRequest.objects.for_team(team_id).filter(id=pr.id).update(+ participant_ids=participant_ids,+ participant_logins=[participants[participant_id] for participant_id in participant_ids],+ participants_synced_at=now,+ updated_at=now,+ )diff --git a/products/signals/backend/management/AGENTS.md b/products/signals/backend/management/AGENTS.mdindex 185984e7d1c5..b2ff8e0f0c46 100644--- a/products/signals/backend/management/AGENTS.md+++ b/products/signals/backend/management/AGENTS.md@@ -183,6 +183,15 @@ records. `--batch-size` bounds each page; the printed `--after` cursor resumes iThe command is idempotent and does not call GitHub, change report state, or enqueuereviewers. See `docs/internal/signals-pr-lifecycle.md` for rollout and cleanup.+## Backfilling inbox summary participants++`uv run manage.py backfill_inbox_summary --team-id <id> --dry-run` previews the next+batch of verified implementation PRs that need participant snapshots. Remove+`--dry-run` to queue the GitHub refresh. `--limit` bounds each invocation (default+100, maximum 1000); use the printed `--after` cursor to continue. Run it without a+cursor again to retry missing snapshots. The worker repairs missing merge times+before checking the seven-day window. Completed snapshots are skipped.+## Repairing a report's cached actionability`SignalReport.latest_actionability` and `latest_already_addressed` cache the two values of a report's newest `actionability_judgment` artefact, so the inbox list can sort and filter on a column instead of walking the artefact log once per report.diff --git a/products/signals/backend/management/commands/backfill_inbox_summary.py b/products/signals/backend/management/commands/backfill_inbox_summary.pynew file mode 100644index 000000000000..e07db2abf4ec--- /dev/null+++ b/products/signals/backend/management/commands/backfill_inbox_summary.py@@ -0,0 +1,52 @@+from argparse import ArgumentParser+from typing import cast+from uuid import UUID++from django.core.management.base import BaseCommand+from django.db.models import Q+from django.utils import timezone++from products.signals.backend.inbox_summary import INBOX_SUMMARY_PERIOD, generated_pull_requests+from products.signals.backend.tasks import refresh_pull_request_participants+from products.tasks.backend.facade import api as tasks_facade+++class Command(BaseCommand):+ help = "Queue a bounded batch of missing inbox participant snapshots. Safe to rerun."++ def add_arguments(self, parser: ArgumentParser) -> None:+ parser.add_argument("--team-id", type=int, required=True)+ parser.add_argument("--after", type=UUID, help="Resume after this pull request UUID.")+ parser.add_argument(+ "--run-after", type=UUID, help="Resume verified URL normalization after this task run UUID."+ )+ parser.add_argument("--limit", type=int, default=100)+ parser.add_argument("--dry-run", action="store_true")++ def handle(self, *args: object, **options: object) -> None:+ team_id = cast(int, options["team_id"])+ if not options["dry_run"]:+ next_run = tasks_facade.normalize_verified_pull_request_urls_batch(+ team_id=team_id, after=cast(UUID | None, options["run_after"])+ )+ if next_run is not None:+ self.stdout.write(f"Normalized verified pull request URLs. Resume with --run-after {next_run}")+ return+ rows = (+ generated_pull_requests(team_id)+ .filter(+ Q(merged_at__gte=timezone.now() - INBOX_SUMMARY_PERIOD) | Q(merged_at__isnull=True),+ state="merged",+ )+ .filter(Q(participants_synced_at__isnull=True) | Q(participant_logins__isnull=True))+ .order_by("id")+ )+ if options["after"]:+ rows = rows.filter(id__gt=options["after"])+ batch = list(rows[: max(1, min(cast(int, options["limit"]), 1000))])+ for pr in batch:+ if not options["dry_run"]:+ refresh_pull_request_participants.delay(team_id=team_id, repository=pr.repository, pr_number=pr.number)+ self.stdout.write(f"{'Would queue' if options['dry_run'] else 'Queued'} {len(batch)} pull requests")+ if batch:+ self.stdout.write(f"Resume with --after {batch[-1].id}")diff --git a/products/signals/backend/migrations/0179_inbox_summary_participants.py b/products/signals/backend/migrations/0179_inbox_summary_participants.pynew file mode 100644index 000000000000..7b1a422f1648--- /dev/null+++ b/products/signals/backend/migrations/0179_inbox_summary_participants.py@@ -0,0 +1,29 @@+# Generated by Django 5.2.17 on 2026-10-02 18:49++import django.contrib.postgres.fields+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1391_organization_provisioning"),+ ("signals", "0178_signalscoutconfig_autovacuum_scale_factor"),+ ]++ operations = [+ migrations.AddField(+ model_name="signalreportpullrequest",+ name="participant_ids",+ field=django.contrib.postgres.fields.ArrayField(+ base_field=models.PositiveBigIntegerField(),+ blank=True,+ null=True,+ size=None,+ ),+ ),+ migrations.AddField(+ model_name="signalreportpullrequest",+ name="participants_synced_at",+ field=models.DateTimeField(blank=True, null=True),+ ),+ ]diff --git a/products/signals/backend/migrations/0180_inbox_summary_merge_index.py b/products/signals/backend/migrations/0180_inbox_summary_merge_index.pynew file mode 100644index 000000000000..27e61c184779--- /dev/null+++ b/products/signals/backend/migrations/0180_inbox_summary_merge_index.py@@ -0,0 +1,20 @@+# Generated by Django 5.2.17 on 2026-10-02 18:50++from django.db import migrations, models++from posthog.migration_helpers import SafeAddIndexConcurrently+++class Migration(migrations.Migration):+ atomic = False++ dependencies = [+ ("signals", "0179_inbox_summary_participants"),+ ]++ operations = [+ SafeAddIndexConcurrently(+ model_name="signalreportpullrequest",+ index=models.Index(fields=["team", "merged_at"], name="signals_pr_team_merged_idx"),+ ),+ ]diff --git a/products/signals/backend/migrations/0181_signalreportpullrequest_participant_logins.py b/products/signals/backend/migrations/0181_signalreportpullrequest_participant_logins.pynew file mode 100644index 000000000000..d504cbbaeb40--- /dev/null+++ b/products/signals/backend/migrations/0181_signalreportpullrequest_participant_logins.py@@ -0,0 +1,23 @@+# Generated by Django 5.2.17 on 2026-10-14 00:00++import django.contrib.postgres.fields+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("signals", "0180_inbox_summary_merge_index"),+ ]++ operations = [+ migrations.AddField(+ model_name="signalreportpullrequest",+ name="participant_logins",+ field=django.contrib.postgres.fields.ArrayField(+ base_field=models.CharField(max_length=255),+ blank=True,+ null=True,+ size=None,+ ),+ ),+ ]diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txtindex a93b96b4bf15..a985165169dc 100644--- a/products/signals/backend/migrations/max_migration.txt+++ b/products/signals/backend/migrations/max_migration.txt@@ -1 +1 @@-0178_signalscoutconfig_autovacuum_scale_factor+0181_signalreportpullrequest_participant_loginsdiff --git a/products/signals/backend/models.py b/products/signals/backend/models.pyindex 00564baf811d..233ddd2a0a29 100644--- a/products/signals/backend/models.py+++ b/products/signals/backend/models.py@@ -1264,6 +1264,9 @@ class SignalReportPullRequest(TeamScopedRootMixin, UUIDModel):review_decision = models.CharField(max_length=20, choices=ReviewDecision, null=True, blank=True)merged_at = models.DateTimeField(null=True, blank=True)checked_at = models.DateTimeField(null=True, blank=True)+ participant_ids = ArrayField(models.PositiveBigIntegerField(), null=True, blank=True)+ participant_logins = ArrayField(models.CharField(max_length=255), null=True, blank=True)+ participants_synced_at = models.DateTimeField(null=True, blank=True)created_at = models.DateTimeField(auto_now_add=True)updated_at = models.DateTimeField(auto_now=True)@@ -1271,6 +1274,7 @@ class SignalReportPullRequest(TeamScopedRootMixin, UUIDModel):constraints = [models.UniqueConstraint(fields=["team", "repository", "number"], name="signals_pr_identity_unique"),]+ indexes = [models.Index(fields=["team", "merged_at"], name="signals_pr_team_merged_idx")]class SignalEmissionRecord(UUIDModel):diff --git a/products/signals/backend/presentation/inbox_summary.py b/products/signals/backend/presentation/inbox_summary.pynew file mode 100644index 000000000000..78200b5bb77a--- /dev/null+++ b/products/signals/backend/presentation/inbox_summary.py@@ -0,0 +1,65 @@+from dataclasses import asdict++from drf_spectacular.utils import extend_schema, extend_schema_serializer+from rest_framework import serializers, viewsets+from rest_framework.permissions import IsAuthenticated+from rest_framework.request import Request+from rest_framework.response import Response++from posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, SessionAuthentication+from posthog.permissions import APIScopePermission, is_service_auth++from products.signals.backend.facade import api as signals_facade+++class InboxSummaryPullRequestSerializer(serializers.Serializer):+ repository = serializers.CharField(help_text="GitHub repository in owner/name format.")+ number = serializers.IntegerField(help_text="GitHub pull request number.")+ url = serializers.URLField(help_text="URL of the GitHub pull request.")+++class InboxSummaryPersonSerializer(serializers.Serializer):+ id = serializers.IntegerField(help_text="Stable GitHub user ID.")+ login = serializers.CharField(help_text="Current GitHub login from the participant snapshot.")+++@extend_schema_serializer(many=False)+class InboxSummarySerializer(serializers.Serializer):+ period_start = serializers.DateTimeField(help_text="Inclusive start of the rolling seven-day period.")+ period_end = serializers.DateTimeField(help_text="Exclusive end of the rolling seven-day period.")+ merged_pr_count = serializers.IntegerField(+ help_text="Distinct verified Self-driving implementation PRs merged in the period."+ )+ people_count = serializers.IntegerField(+ allow_null=True, help_text="Distinct human approvers and mergers, or null while incomplete."+ )+ participation_complete = serializers.BooleanField(+ help_text="Whether every counted PR has a complete participant snapshot."+ )+ pull_requests = InboxSummaryPullRequestSerializer(+ many=True, help_text="Verified Self-driving implementation PRs merged in the period."+ )+ people = InboxSummaryPersonSerializer(+ many=True,+ allow_null=True,+ help_text="Distinct human approvers and mergers, or null while participation is incomplete.",+ )+++class InboxSummaryViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):+ serializer_class = InboxSummarySerializer+ authentication_classes = [SessionAuthentication, PersonalAPIKeyAuthentication, OAuthAccessTokenAuthentication]+ permission_classes = [IsAuthenticated, APIScopePermission]+ scope_object = "task"+ requires_resource_level_access = True+ pagination_class = None++ @extend_schema(responses=InboxSummarySerializer)+ def list(self, request: Request, **kwargs: object) -> Response:+ summary = signals_facade.get_inbox_summary(+ team_id=self.team_id,+ user=request.user,+ service_auth=is_service_auth(request),+ )+ return Response(InboxSummarySerializer(asdict(summary)).data)diff --git a/products/signals/backend/pull_requests.py b/products/signals/backend/pull_requests.pyindex 8d9691c6de55..514178aa66d4 100644--- a/products/signals/backend/pull_requests.py+++ b/products/signals/backend/pull_requests.py@@ -4,9 +4,12 @@ from enum import StrEnumfrom functools import partialfrom typing import TYPE_CHECKING+from django.core.cache import cachefrom django.db import transactionfrom django.utils import timezone+import structlog+from products.signals.backend.artefact_attribution import ArtefactAttributionfrom products.signals.backend.artefact_schemas import PullRequestLinkfrom products.signals.backend.claim_display_name import claim_display_name@@ -15,6 +18,10 @@ from products.signals.backend.models import SignalReport, SignalReportArtefact,if TYPE_CHECKING:from products.signals.backend.report_assignments import PullRequestDetails+logger = structlog.get_logger(__name__)++PARTICIPANT_REFRESH_DEDUPE_SECONDS = 60+class PullRequestStateSource(StrEnum):GITHUB = "github"@@ -22,6 +29,39 @@ class PullRequestStateSource(StrEnum):LEGACY_ASSIGNMENT = "legacy_assignment"+def schedule_participant_refresh(pr: SignalReportPullRequest) -> None:+ from products.signals.backend.tasks import refresh_pull_request_participants++ if pr.state == SignalReportPullRequest.State.MERGED and pr.participants_synced_at is None:++ def enqueue() -> None:+ key = f"signals:participant-refresh:{pr.id}"+ claimed = False+ try:+ claimed = cache.add(key, True, timeout=PARTICIPANT_REFRESH_DEDUPE_SECONDS)+ if not claimed:+ return+ except Exception:+ logger.exception("signals_participant_refresh_dedupe_failed", team_id=pr.team_id, pr_id=str(pr.id))+ try:+ refresh_pull_request_participants.delay(+ team_id=pr.team_id, repository=pr.repository, pr_number=pr.number+ )+ except Exception:+ if claimed:+ try:+ cache.delete(key)+ except Exception:+ logger.exception(+ "signals_participant_refresh_dedupe_cleanup_failed",+ team_id=pr.team_id,+ pr_id=str(pr.id),+ )+ logger.exception("signals_participant_refresh_enqueue_failed", team_id=pr.team_id, pr_id=str(pr.id))++ transaction.on_commit(enqueue)++def reconcile_reports_for_pull_request(*, team_id: int, pr_id: str) -> None:from products.signals.backend.implementation_pr import report_ids_for_implementation_prfrom products.signals.backend.supersession import schedule_report_replacements@@ -120,6 +160,8 @@ def link_pull_request(schedule_pull_request_label(team_id=report.team_id, report_id=str(report.id), pr_url=pr.url, pr_state=pr.state)+ if state_source != PullRequestStateSource.LEGACY_ASSIGNMENT:+ schedule_participant_refresh(pr)return pr@@ -248,6 +290,7 @@ def update_pull_request_state(update_fields.append("merged_at")pr.checked_at = timezone.now()pr.save(update_fields=update_fields)+ schedule_participant_refresh(pr)for report in reports:apply_report_completion(report)return len(reports)diff --git a/products/signals/backend/routes.py b/products/signals/backend/routes.pyindex 6d9cc69ec86c..cfbb0c87a8e9 100644--- a/products/signals/backend/routes.py+++ b/products/signals/backend/routes.py@@ -1,6 +1,7 @@from posthog.api.routing import RouterRegistryimport products.signals.backend.views as signals+from products.signals.backend.presentation.inbox_summary import InboxSummaryViewSetfrom products.signals.backend.presentation.scout_rubrics import SignalScoutRubricViewSetfrom products.signals.backend.scout_chat import SignalScoutChatTaskViewSetfrom products.signals.backend.scout_harness.views import (@@ -18,6 +19,9 @@ from products.signals.backend.views import SignalViewSetdef register_routes(routers: RouterRegistry) -> None:+ routers.projects.register(+ r"signals/inbox_summary", InboxSummaryViewSet, "project_signals_inbox_summary", ["team_id"]+ )routers.projects.register(r"signals/scout/rubrics", SignalScoutRubricViewSet, "project_signals_scout_rubrics", ["team_id"])diff --git a/products/signals/backend/tasks.py b/products/signals/backend/tasks.pyindex 823a1dd9465c..147a06327a22 100644--- a/products/signals/backend/tasks.py+++ b/products/signals/backend/tasks.py@@ -32,6 +32,7 @@ from products.signals.backend.implementation_dispatch_tasks import (sweep_implementation_dispatches as sweep_implementation_dispatches,)from products.signals.backend.implementation_pr import PrCloseReason, close_implementation_pr_for_report+from products.signals.backend.inbox_summary import sync_pull_request_participantsfrom products.signals.backend.models import (SignalReport,SignalReportPullRequest,@@ -78,6 +79,22 @@ from products.tasks.backend.facade.repo_activity import RepositoryCommitActivitylogger = structlog.get_logger(__name__)+@shared_task(+ name="products.signals.backend.tasks.refresh_pull_request_participants",+ ignore_result=True,+ bind=True,+ autoretry_for=(GitHubEgressBudgetExhausted, GitHubIntegrationError),+ retry_backoff=True,+ max_retries=5,+)+@with_team_scope()+def refresh_pull_request_participants(self, team_id: int, repository: str, pr_number: int) -> None:+ try:+ sync_pull_request_participants(team_id=team_id, repository=repository, pr_number=pr_number)+ except GitHubRateLimitError as error:+ raise self.retry(exc=error, countdown=max(error.retry_after or 0, 60))++@shared_task(name="products.signals.backend.tasks.refresh_pull_request_review_decision",ignore_result=True,@@ -94,6 +111,10 @@ def refresh_pull_request_review_decision(team_id: int, repository: str, pr_numbe)if pr is None:return+ if pr.state == SignalReportPullRequest.State.MERGED:+ from products.signals.backend.pull_requests import schedule_participant_refresh++ schedule_participant_refresh(pr)github = GitHubIntegration.first_for_team_repository(team_id,diff --git a/products/signals/backend/test/test_inbox_summary.py b/products/signals/backend/test/test_inbox_summary.pynew file mode 100644index 000000000000..48debd816254--- /dev/null+++ b/products/signals/backend/test/test_inbox_summary.py@@ -0,0 +1,493 @@+from datetime import UTC, datetime, timedelta+from io import StringIO++import time_machine+from posthog.test.base import APIBaseTest+from unittest.mock import MagicMock, patch++from django.core.management import call_command+from django.test import SimpleTestCase++from celery.exceptions import Retry+from parameterized import parameterized++from posthog.constants import AvailableFeature+from posthog.egress.github.transport import GitHubEgressBudgetExhausted, GitHubRateLimitError+from posthog.egress.limiter.policies import Priority+from posthog.models import Organization, OrganizationMembership, Team, User+from posthog.models.github_integration_base import GitHubIntegrationError+from posthog.models.integration import GitHubIntegration, Integration+from posthog.models.user_integration import UserIntegration++from products.access_control.backend.models.access_control import AccessControl+from products.signals.backend.inbox_summary import sync_pull_request_participants+from products.signals.backend.models import SignalReport, SignalReportPullRequest, SignalReportTask+from products.signals.backend.pull_requests import schedule_participant_refresh, update_pull_request_state+from products.signals.backend.tasks import refresh_pull_request_participants, refresh_pull_request_review_decision+from products.tasks.backend.facade import api as tasks_facade+from products.tasks.backend.models import Channel, Task, TaskRun++NOW = datetime(2026, 9, 20, 12, tzinfo=UTC)+MERGED_AT = NOW - timedelta(days=1)+++@time_machine.travel(NOW, tick=False)+class TestInboxSummary(APIBaseTest):+ def make_pr(+ self,+ number: int = 1,+ *,+ team: Team | None = None,+ merged_at: datetime | None = MERGED_AT,+ participant_ids: list[int] | None = None,+ participant_logins: list[str] | None = None,+ verified: bool = True,+ relationship: str = "implementation",+ state: str = "merged",+ ) -> SignalReportPullRequest:+ team = team or self.team+ if participant_ids is not None and participant_logins is None:+ participant_logins = [f"user-{participant_id}" for participant_id in participant_ids]+ pr = SignalReportPullRequest.objects.for_team(team.id).create(+ team=team,+ repository="example/app",+ number=number,+ url=f"https://github.com/example/app/pull/{number}",+ state=state,+ merged_at=merged_at,+ participant_ids=participant_ids,+ participant_logins=participant_logins,+ participants_synced_at=NOW if participant_ids is not None else None,+ )+ report = SignalReport.objects.create(team=team, title="Example report", summary="Example finding")+ task = Task.objects.create(team=team, title="Example task", description="", origin_product="signals")+ SignalReportTask.objects.create(team=team, report=report, task=task, relationship=relationship)+ run = TaskRun.objects.create(team=team, task=task, status=TaskRun.Status.COMPLETED)+ TaskRun.objects.filter(id=run.id).update(+ output={"pr_url": pr.url}, state={"verified_pr_urls": [pr.url] if verified else []}+ )+ return pr++ def summary(self, query: str = "") -> dict:+ response = self.client.get(f"/api/projects/{self.team.id}/signals/inbox_summary/{query}")+ assert response.status_code == 200, response.data+ return response.json()++ def test_counts_verified_implementation_prs_and_distinct_people(self) -> None:+ self.make_pr(1, participant_ids=[10, 20])+ self.make_pr(2, participant_ids=[20, 30])+ self.make_pr(3, participant_ids=[40], verified=False)+ self.make_pr(4, participant_ids=[50], relationship="research")+ self.make_pr(5, participant_ids=[60], relationship="discussion")+ self.make_pr(6, participant_ids=[70], state="open")+ foreign_team = Team.objects.create(organization=self.organization)+ self.make_pr(7, team=foreign_team, participant_ids=[80])+ with patch("products.signals.backend.inbox_summary.GitHubIntegration.first_for_team_repository") as github:+ result = self.summary("?scope=for-you&reviewer=123")+ github.assert_not_called()+ assert result == {+ "period_start": "2026-09-13T12:00:00Z",+ "period_end": "2026-09-20T12:00:00Z",+ "merged_pr_count": 2,+ "people_count": 3,+ "participation_complete": True,+ "pull_requests": [+ {"repository": "example/app", "number": 1, "url": "https://github.com/example/app/pull/1"},+ {"repository": "example/app", "number": 2, "url": "https://github.com/example/app/pull/2"},+ ],+ "people": [+ {"id": 10, "login": "user-10"},+ {"id": 20, "login": "user-20"},+ {"id": 30, "login": "user-30"},+ ],+ }++ def test_a_pr_with_multiple_task_associations_counts_once(self) -> None:+ self.make_pr(participant_ids=[10])+ gate = SignalReportTask.objects.get(team=self.team)+ report = SignalReport.objects.create(team=self.team, title="Second report", summary="Example")+ SignalReportTask.objects.create(+ team=self.team, report=report, task_id=gate.task_id, relationship="implementation"+ )+ assert self.summary()["merged_pr_count"] == 1++ def test_attribution_uses_repository_and_number_not_the_first_attached_url(self) -> None:+ pr = self.make_pr(1, participant_ids=[10])+ SignalReportPullRequest.objects.for_team(self.team.id).filter(id=pr.id).update(+ url="https://github.com/EXAMPLE/APP/pull/1/files"+ )+ TaskRun.objects.filter(team=self.team).update(+ state={"verified_pr_urls": ["https://github.com/Example/App/pull/1"]}+ )+ self.make_pr(10, verified=False, participant_ids=[20])+ assert self.summary()["merged_pr_count"] == 0+ tasks_facade.normalize_verified_pull_request_urls_batch(team_id=self.team.id)+ assert self.summary()["merged_pr_count"] == 1++ def test_window_is_half_open_and_uses_merge_time(self) -> None:+ self.make_pr(1, merged_at=NOW - timedelta(days=7), participant_ids=[])+ self.make_pr(2, merged_at=NOW - timedelta(days=7, microseconds=1), participant_ids=[])+ self.make_pr(3, merged_at=NOW, participant_ids=[])+ self.make_pr(4, merged_at=None, participant_ids=[])+ assert self.summary()["merged_pr_count"] == 1++ def test_missing_participation_is_unknown_not_a_partial_count(self) -> None:+ self.make_pr(1, participant_ids=[10])+ self.make_pr(2)+ result = self.summary()+ assert result["merged_pr_count"] == 2+ assert result["people_count"] is None+ assert result["participation_complete"] is False++ def test_no_merges_returns_zero(self) -> None:+ result = self.summary()+ assert result["merged_pr_count"] == 0+ assert result["people_count"] == 0+ assert result["participation_complete"] is True+ assert result["pull_requests"] == []+ assert result["people"] == []++ def test_another_project_is_not_accessible(self) -> None:+ other_team = Team.objects.create(organization=Organization.objects.create(name="Other organization"))+ self.make_pr(team=other_team, participant_ids=[10])+ assert self.client.get(f"/api/projects/{other_team.id}/signals/inbox_summary/").status_code in (403, 404)++ def test_access_to_one_task_does_not_grant_access_to_project_totals(self) -> None:+ self.make_pr(participant_ids=[10])+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},+ ]+ self.organization.save()+ member = User.objects.create_and_join(self.organization, "[email protected]", "test-password")+ membership = OrganizationMembership.objects.get(user=member, organization=self.organization)+ AccessControl.objects.create(+ team=self.team, resource="task", access_level="none", organization_member=membership+ )+ AccessControl.objects.create(+ team=self.team,+ resource="task",+ resource_id=str(Task.objects.get(team=self.team).id),+ access_level="editor",+ organization_member=membership,+ )+ self.client.force_login(member)+ assert self.client.get(f"/api/projects/{self.team.id}/signals/inbox_summary/").status_code == 403++ def test_explicitly_denied_tasks_do_not_contribute_to_summary(self) -> None:+ self.make_pr(1, participant_ids=[10])+ denied_task_id = SignalReportTask.objects.get(team=self.team).task_id+ self.make_pr(2, participant_ids=[20])+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},+ ]+ self.organization.save()+ member = User.objects.create_and_join(self.organization, "[email protected]", "test-password")+ membership = OrganizationMembership.objects.get(user=member, organization=self.organization)+ AccessControl.objects.create(+ team=self.team,+ resource="task",+ resource_id=str(denied_task_id),+ access_level="none",+ organization_member=membership,+ )+ self.client.force_login(member)++ result = self.summary()++ assert result["merged_pr_count"] == 1+ assert result["pull_requests"] == [+ {"repository": "example/app", "number": 2, "url": "https://github.com/example/app/pull/2"}+ ]++ def test_tasks_in_another_users_personal_channel_do_not_contribute_to_summary(self) -> None:+ self.make_pr(participant_ids=[10])+ personal = Channel.objects.create(+ team=self.team,+ name="me",+ channel_type=Channel.ChannelType.PERSONAL,+ created_by=self.user,+ )+ Task.objects.filter(team=self.team).update(channel=personal)+ member = User.objects.create_and_join(self.organization, "[email protected]", "test-password")+ self.client.force_login(member)++ result = self.summary()++ assert result["merged_pr_count"] == 0+ assert result["pull_requests"] == []++ def test_authentication_is_required(self) -> None:+ self.client.logout()+ assert self.client.get(f"/api/projects/{self.team.id}/signals/inbox_summary/").status_code in (401, 403)++ def github(self) -> MagicMock:+ github = MagicMock()+ github.installation_can_access_repository.return_value = True+ github.get_pull_request.return_value = {+ "success": True,+ "merged": True,+ "merged_at": MERGED_AT.isoformat(),+ "merged_by": {"id": 10, "type": "User", "login": "example-merger"},+ }+ github.get_pull_request_reviews.return_value = []+ return github++ def sync(self, github: MagicMock) -> None:+ with patch(+ "products.signals.backend.inbox_summary.GitHubIntegration.first_for_team_repository", return_value=github+ ):+ sync_pull_request_participants(team_id=self.team.id, repository="example/app", pr_number=1)++ def test_sync_keeps_human_approvals_before_merge_and_deduplicates(self) -> None:+ pr = self.make_pr(merged_at=None)+ github = self.github()+ github.get_pull_request_reviews.return_value = [+ {+ "state": state,+ "submitted_at": submitted_at.isoformat(),+ "user": {"id": user_id, "type": user_type, "login": login},+ }+ for state, submitted_at, user_id, user_type, login in [+ ("APPROVED", NOW - timedelta(days=10), 20, "User", "example-approver"),+ ("APPROVED", MERGED_AT, 10, "User", "example-merger"),+ ("APPROVED", MERGED_AT, 20, "User", "renamed-approver"),+ ("DISMISSED", MERGED_AT, 30, "User", "dismissed-approver"),+ ("CHANGES_REQUESTED", MERGED_AT, 40, "User", "example-reviewer"),+ ("APPROVED", NOW, 50, "User", "late-approver"),+ ("APPROVED", MERGED_AT, 60, "Bot", "example-app"),+ ("APPROVED", MERGED_AT, 70, "User", "example[bot]"),+ ]+ ]+ self.sync(github)+ self.sync(github)+ pr.refresh_from_db()+ assert pr.merged_at == MERGED_AT+ assert pr.participant_ids == [10, 20]+ assert pr.participant_logins == ["example-merger", "renamed-approver"]+ assert pr.participants_synced_at == NOW++ def test_sync_uses_the_attributed_tasks_personal_github_integration(self) -> None:+ pr = self.make_pr(merged_at=None)+ personal = UserIntegration.objects.create(user=self.user, kind="github", integration_id="123")+ task = Task.objects.get(team=self.team)+ task.created_by = self.user+ task.github_user_integration = personal+ task.save(update_fields=["created_by", "github_user_integration", "updated_at"])+ github = self.github()+ with (+ patch(+ "products.signals.backend.inbox_summary.UserGitHubIntegration", return_value=github+ ) as personal_github,+ patch("products.signals.backend.inbox_summary.GitHubIntegration.first_for_team_repository") as team_github,+ ):+ sync_pull_request_participants(team_id=self.team.id, repository="example/app", pr_number=1)+ personal_github.assert_called_once_with(personal, source="signals_inbox_summary", priority=Priority.BATCH)+ github.installation_can_access_repository.assert_called_once_with("example/app", raise_on_transient=True)+ team_github.assert_not_called()+ pr.refresh_from_db()+ assert pr.participant_ids == [10]+ assert pr.participant_logins == ["example-merger"]++ def test_sync_falls_back_when_the_attributed_integration_lost_repository_access(self) -> None:+ pr = self.make_pr(merged_at=None)+ integration = Integration.objects.create(team=self.team, kind="github", integration_id="123")+ task = Task.objects.get(team=self.team)+ task.github_integration = integration+ task.save(update_fields=["github_integration", "updated_at"])+ fallback = self.github()+ with (+ patch.object(GitHubIntegration, "installation_can_access_repository", return_value=False) as access,+ patch.object(GitHubIntegration, "first_for_team_repository", return_value=fallback) as find_fallback,+ ):+ sync_pull_request_participants(team_id=self.team.id, repository="example/app", pr_number=1)+ access.assert_called_once_with("example/app", raise_on_transient=True)+ find_fallback.assert_called_once_with(+ self.team.id, "example/app", source="signals_inbox_summary", priority=Priority.BATCH+ )+ pr.refresh_from_db()+ assert pr.participant_ids == [10]++ def test_sync_tries_a_team_reader_after_a_personal_reader_exhausts_its_budget(self) -> None:+ pr = self.make_pr(merged_at=None)+ personal = UserIntegration.objects.create(user=self.user, kind="github", integration_id="123")+ task = Task.objects.get(team=self.team)+ task.created_by = self.user+ task.github_user_integration = personal+ task.save(update_fields=["created_by", "github_user_integration", "updated_at"])+ attributed = self.github()+ attributed.installation_can_access_repository.side_effect = GitHubEgressBudgetExhausted("shed")+ fallback = self.github()+ with (+ patch("products.signals.backend.inbox_summary.UserGitHubIntegration", return_value=attributed),+ patch.object(GitHubIntegration, "first_for_team_repository", return_value=fallback),+ ):+ sync_pull_request_participants(team_id=self.team.id, repository="example/app", pr_number=1)+ pr.refresh_from_db()+ assert pr.participant_ids == [10]++ def test_sync_retries_when_repository_access_probes_fail_transiently(self) -> None:+ self.make_pr(merged_at=None)+ integration = Integration.objects.create(team=self.team, kind="github", integration_id="123")+ task = Task.objects.get(team=self.team)+ task.github_integration = integration+ task.save(update_fields=["github_integration", "updated_at"])+ error = GitHubIntegrationError("GitHub unavailable", status_code=503)+ with (+ patch.object(GitHubIntegration, "installation_can_access_repository", side_effect=error),+ patch.object(GitHubIntegration, "first_for_team_repository", return_value=None),+ self.assertRaises(GitHubIntegrationError),+ ):+ sync_pull_request_participants(team_id=self.team.id, repository="example/app", pr_number=1)++ def test_refresh_uses_githubs_retry_delay(self) -> None:+ error = GitHubRateLimitError("rate limited", retry_after=120)+ with (+ patch("products.signals.backend.tasks.sync_pull_request_participants", side_effect=error),+ patch.object(refresh_pull_request_participants, "retry", side_effect=Retry()) as retry,+ self.assertRaises(Retry),+ ):+ refresh_pull_request_participants._orig_run(team_id=self.team.id, repository="example/app", pr_number=1)+ retry.assert_called_once_with(exc=error, countdown=120)++ def test_participant_refreshes_for_the_same_pr_are_coalesced(self) -> None:+ pr = self.make_pr()+ with patch("products.signals.backend.tasks.refresh_pull_request_participants.delay") as enqueue:+ with self.captureOnCommitCallbacks(execute=True):+ schedule_participant_refresh(pr)+ schedule_participant_refresh(pr)+ enqueue.assert_called_once_with(team_id=self.team.id, repository="example/app", pr_number=1)++ def test_participant_enqueue_failure_does_not_stop_the_review_refresh(self) -> None:+ pr = self.make_pr()+ github = MagicMock()+ github.get_pull_request_snapshot.return_value = {"success": True, "review_decision": "approved"}+ with (+ patch(+ "products.signals.backend.tasks.refresh_pull_request_participants.delay",+ side_effect=RuntimeError("broker unavailable"),+ ) as enqueue,+ patch("products.signals.backend.pull_requests.cache.delete", side_effect=RuntimeError("cache unavailable")),+ patch("products.signals.backend.tasks.GitHubIntegration.first_for_team_repository", return_value=github),+ ):+ with self.captureOnCommitCallbacks(execute=True):+ refresh_pull_request_review_decision.run(team_id=self.team.id, repository="example/app", pr_number=1)+ enqueue.assert_called_once_with(team_id=self.team.id, repository="example/app", pr_number=1)+ pr.refresh_from_db()+ assert pr.review_decision == SignalReportPullRequest.ReviewDecision.APPROVED++ def test_cache_failure_does_not_stop_participant_or_review_refresh(self) -> None:+ pr = self.make_pr()+ github = MagicMock()+ github.get_pull_request_snapshot.return_value = {"success": True, "review_decision": "approved"}+ with (+ patch("products.signals.backend.pull_requests.cache.add", side_effect=RuntimeError("cache unavailable")),+ patch("products.signals.backend.tasks.refresh_pull_request_participants.delay") as enqueue,+ patch("products.signals.backend.tasks.GitHubIntegration.first_for_team_repository", return_value=github),+ ):+ with self.captureOnCommitCallbacks(execute=True):+ refresh_pull_request_review_decision.run(team_id=self.team.id, repository="example/app", pr_number=1)+ enqueue.assert_called_once_with(team_id=self.team.id, repository="example/app", pr_number=1)+ pr.refresh_from_db()+ assert pr.review_decision == SignalReportPullRequest.ReviewDecision.APPROVED++ @parameterized.expand([("missing_merger",), ("missing_review_page",), ("invalid_approval_time",)])+ def test_incomplete_github_data_does_not_store_partial_people(self, failure: str) -> None:+ pr = self.make_pr(merged_at=None)+ github = self.github()+ if failure == "missing_merger":+ github.get_pull_request.return_value["merged_by"] = None+ elif failure == "missing_review_page":+ github.get_pull_request_reviews.side_effect = GitHubIntegrationError("Missing page")+ else:+ github.get_pull_request_reviews.return_value = [{"state": "APPROVED", "submitted_at": "invalid"}]+ with self.assertRaises(GitHubIntegrationError):+ self.sync(github)+ pr.refresh_from_db()+ assert pr.merged_at == MERGED_AT+ assert pr.participant_ids is None+ assert pr.participant_logins is None+ assert pr.participants_synced_at is None++ def test_an_old_missing_merge_time_is_repaired_without_fetching_reviews(self) -> None:+ pr = self.make_pr(merged_at=None)+ github = self.github()+ github.get_pull_request.return_value["merged_at"] = (NOW - timedelta(days=30)).isoformat()+ self.sync(github)+ github.get_pull_request_reviews.assert_not_called()+ pr.refresh_from_db()+ assert pr.merged_at == NOW - timedelta(days=30)++ def test_a_failed_refresh_keeps_the_last_complete_snapshot(self) -> None:+ pr = self.make_pr(participant_ids=[10, 20])+ github = self.github()+ github.get_pull_request_reviews.side_effect = GitHubIntegrationError("Reviews not available")+ with self.assertRaises(GitHubIntegrationError):+ self.sync(github)+ pr.refresh_from_db()+ assert pr.participant_ids == [10, 20]+ assert pr.participant_logins == ["user-10", "user-20"]+ assert pr.participants_synced_at == NOW++ @parameterized.expand([("manual", False, "implementation"), ("research", True, "research")])+ def test_sync_skips_unattributed_prs(self, _name: str, verified: bool, relationship: str) -> None:+ self.make_pr(verified=verified, relationship=relationship)+ github = self.github()+ self.sync(github)+ github.get_pull_request.assert_not_called()++ def test_merge_schedules_refresh_after_commit(self) -> None:+ self.make_pr(state="open", merged_at=None)+ with patch("products.signals.backend.tasks.refresh_pull_request_participants.delay") as enqueue:+ with self.captureOnCommitCallbacks(execute=True):+ update_pull_request_state(+ team_id=self.team.id, repository="example/app", number=1, state="merged", merged_at=MERGED_AT+ )+ enqueue.assert_not_called()+ enqueue.assert_called_once_with(team_id=self.team.id, repository="example/app", pr_number=1)++ def test_backfill_is_bounded_resumable_and_includes_missing_merge_times(self) -> None:+ self.make_pr(1, merged_at=None)+ self.make_pr(2)+ self.make_pr(3, merged_at=NOW - timedelta(days=30))+ existing = self.make_pr(4, participant_ids=[10])+ SignalReportPullRequest.objects.for_team(self.team.id).filter(id=existing.id).update(participant_logins=None)+ output = StringIO()+ with patch("products.signals.backend.tasks.refresh_pull_request_participants.delay") as enqueue:+ call_command("backfill_inbox_summary", team_id=self.team.id, limit=1, dry_run=True, stdout=output)+ enqueue.assert_not_called()+ output = StringIO()+ call_command("backfill_inbox_summary", team_id=self.team.id, limit=1, stdout=output)+ assert enqueue.call_count == 1+ cursor = output.getvalue().split("--after ")[1].strip()+ call_command("backfill_inbox_summary", team_id=self.team.id, after=cursor, stdout=StringIO())+ assert enqueue.call_count == 3+ assert {call.kwargs["pr_number"] for call in enqueue.call_args_list} == {1, 2, 4}+++class TestPullRequestReviewPagination(SimpleTestCase):+ @parameterized.expand([("../example/app", 1), ("example/app?path=other", 1), ("example/app", 0)])+ def test_rejects_invalid_identity_before_network_access(self, repository: str, number: int) -> None:+ github = GitHubIntegration(MagicMock(kind="github"), source="test", priority=Priority.CRITICAL)+ with patch.object(github, "_installation_authenticated_get_pages") as fetch:+ with self.assertRaises(GitHubIntegrationError):+ github.get_pull_request_reviews(repository, number)+ fetch.assert_not_called()++ def test_reads_every_page(self) -> None:+ github = GitHubIntegration(MagicMock(kind="github"), source="test", priority=Priority.CRITICAL)+ first = MagicMock(+ status_code=200, links={"next": {"url": "https://api.github.com/repos/example/app/pulls/1/reviews?page=2"}}+ )+ first.json.return_value = [{"id": index} for index in range(100)]+ second = MagicMock(status_code=200, links={})+ second.json.return_value = [{"id": 100}]+ with patch.object(github, "_installation_authenticated_get", side_effect=[first, second]):+ assert len(github.get_pull_request_reviews("example/app", 1)) == 101++ def test_rejects_partial_pages(self) -> None:+ github = GitHubIntegration(MagicMock(kind="github"), source="test", priority=Priority.CRITICAL)+ with patch.object(github, "_installation_authenticated_get_pages", return_value=([MagicMock()], False)):+ with self.assertRaises(GitHubIntegrationError):+ github.get_pull_request_reviews("example/app", 1)diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex 74f561355235..63b063db1305 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -102,6 +102,45 @@ export interface SignalTeamConfigApi {readonly updated_at: string}+export interface InboxSummaryPullRequestApi {+ /** GitHub repository in owner/name format. */+ repository: string+ /** GitHub pull request number. */+ number: number+ /** URL of the GitHub pull request. */+ url: string+}++export interface InboxSummaryPersonApi {+ /** Stable GitHub user ID. */+ id: number+ /** Current GitHub login from the participant snapshot. */+ login: string+}++export interface InboxSummaryApi {+ /** Inclusive start of the rolling seven-day period. */+ period_start: string+ /** Exclusive end of the rolling seven-day period. */+ period_end: string+ /** Distinct verified Self-driving implementation PRs merged in the period. */+ merged_pr_count: number+ /**+ * Distinct human approvers and mergers, or null while incomplete.+ * @nullable+ */+ people_count: number | null+ /** Whether every counted PR has a complete participant snapshot. */+ participation_complete: boolean+ /** Verified Self-driving implementation PRs merged in the period. */+ pull_requests: InboxSummaryPullRequestApi[]+ /**+ * Distinct human approvers and mergers, or null while participation is incomplete.+ * @nullable+ */+ people: InboxSummaryPersonApi[] | null+}+export interface PauseStateResponseApi {/*** The timestamp the pipeline is paused until, or null if not paused/not running.diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.tsindex 200507e9b330..f5dc1aa2ec20 100644--- a/products/signals/frontend/generated/api.ts+++ b/products/signals/frontend/generated/api.ts@@ -21,6 +21,7 @@ import type {FleetFindingsSummaryApi,ForgetRequestApi,ForgetResponseApi,+ InboxSummaryApi,LighthouseAuditRequestApi,LighthouseAuditResponseApi,PaginatedPauseStateResponseListApi,@@ -218,6 +219,17 @@ export const signalsConfigCreate = async (})}+export const getSignalsInboxSummaryListUrl = (projectId: string) => {+ return `/api/projects/${projectId}/signals/inbox_summary/`+}++export const signalsInboxSummaryList = async (projectId: string, options?: RequestInit): Promise<InboxSummaryApi> => {+ return apiMutator<InboxSummaryApi>(getSignalsInboxSummaryListUrl(projectId), {+ ...options,+ method: 'GET',+ })+}+export const getSignalsProcessingListUrl = (projectId: string, params?: SignalsProcessingListParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/signals/frontend/inbox/InboxScene.stories.tsx b/products/signals/frontend/inbox/InboxScene.stories.tsxindex 0aafdfeb760b..fbfc37e4628f 100644--- a/products/signals/frontend/inbox/InboxScene.stories.tsx+++ b/products/signals/frontend/inbox/InboxScene.stories.tsx@@ -107,6 +107,51 @@ type Story = StoryObjexport const Inbox: Story = {}+const valueSummaryMocks = mswDecorator({+ get: {+ '/api/projects/:team_id/signals/inbox_summary/': {+ period_start: '2026-06-04T00:00:00Z',+ period_end: '2026-06-11T00:00:00Z',+ merged_pr_count: 12,+ people_count: 5,+ participation_complete: true,+ pull_requests: Array.from({ length: 12 }, (_, index) => ({+ repository: index % 3 === 0 ? 'PostHog/posthog-js' : 'PostHog/posthog',+ number: 111094 - index,+ url: `https://github.com/${index % 3 === 0 ? 'PostHog/posthog-js' : 'PostHog/posthog'}/pull/${111094 - index}`,+ })),+ people: [+ { id: 1, login: 'sam-example' },+ { id: 2, login: 'alex-example' },+ { id: 3, login: 'riley-example' },+ { id: 4, login: 'taylor-example' },+ { id: 5, login: 'jordan-example' },+ ],+ },+ },+})++export const WithValueSummary: Story = {+ parameters: {+ featureFlags: {+ ...meta.parameters?.featureFlags,+ [FEATURE_FLAGS.SIGNALS_INBOX_VALUE_SUMMARY]: true,+ },+ },+ decorators: [valueSummaryMocks],+}++export const LegacyWithValueSummary: Story = {+ parameters: {+ featureFlags: {+ ...meta.parameters?.featureFlags,+ [FEATURE_FLAGS.SIGNALS_INBOX_VALUE_SUMMARY]: true,+ [FEATURE_FLAGS.INBOX_REDESIGN]: false,+ },+ },+ decorators: [valueSummaryMocks],+}+function reportWithEvidenceItems(count: number): Story {return {decorators: [diff --git a/products/signals/frontend/inbox/InboxScene.tsx b/products/signals/frontend/inbox/InboxScene.tsxindex fcab9a46d944..e47ff4f14538 100644--- a/products/signals/frontend/inbox/InboxScene.tsx+++ b/products/signals/frontend/inbox/InboxScene.tsx@@ -24,6 +24,7 @@ import { InboxWelcome } from './components/onboarding/InboxWelcome'import { ScratchpadPanel } from './components/scratchpad/ScratchpadPanel'import { InboxListViewLegacy } from './components/shell/InboxListViewLegacy'import { InboxTabBar } from './components/shell/InboxTabBar'+import { InboxValueSummary } from './components/shell/InboxValueSummary'import { ReportsTab } from './components/tabs/ReportsTab'import { RunsTab } from './components/tabs/RunsTab'import { SettingsTab } from './components/tabs/SettingsTab'@@ -297,6 +298,9 @@ export function InboxScene(): JSX.Element {isn't set up, the list view itself swaps in the welcome page; the banner sitsabove the otherwise-normal inbox when there's already work to keep. */}{onboardingMode === 'banner' && <InboxOnboardingBanner />}+ {onboardingMode !== 'takeover' && onboardingMode !== 'pending' && (+ <InboxValueSummary visible={!showDetail} />+ )}{isRedesign ? <InboxListView /> : <InboxListViewLegacy />}</div></div>diff --git a/products/signals/frontend/inbox/components/shell/InboxSummaryPeoplePopover.tsx b/products/signals/frontend/inbox/components/shell/InboxSummaryPeoplePopover.tsxnew file mode 100644index 000000000000..138d5e498843--- /dev/null+++ b/products/signals/frontend/inbox/components/shell/InboxSummaryPeoplePopover.tsx@@ -0,0 +1,56 @@+import { useState } from 'react'++import { Popover } from '@posthog/lemon-ui'++import type { InboxSummaryPersonApi } from '../../../generated/api.schemas'++export function InboxSummaryPeoplePopover({ people }: { people: InboxSummaryPersonApi[] }): JSX.Element {+ const [visible, setVisible] = useState(false)+ const count = people.length++ return (+ <Popover+ visible={visible}+ placement="bottom-start"+ showArrow+ padded={false}+ onClickOutside={() => setVisible(false)}+ onMouseEnterInside={() => setVisible(true)}+ onMouseLeaveInside={() => setVisible(false)}+ overlay={+ <div+ role="dialog"+ aria-label="People who approved or merged"+ className="max-h-80 w-64 overflow-y-auto p-2"+ >+ <p className="m-0 px-1 pb-1 text-xs font-semibold">People who approved or merged</p>+ {people.length > 0 ? (+ <ul className="m-0 flex list-none flex-col gap-0.5 p-0">+ {people.map((person) => (+ <li key={person.id} className="truncate rounded px-1 py-0.5 text-xs">+ @{person.login}+ </li>+ ))}+ </ul>+ ) : (+ <p className="m-0 px-1 text-xs text-secondary">No people approved or merged these PRs.</p>+ )}+ </div>+ }+ >+ <button+ type="button"+ className="m-0 inline cursor-pointer border-0 bg-transparent p-0 font-semibold text-default underline decoration-dotted underline-offset-2 hover:text-accent"+ aria-label={`Show ${count} ${count === 1 ? 'person' : 'people'}`}+ aria-haspopup="dialog"+ aria-expanded={visible}+ data-attr="inbox-value-summary-people"+ onMouseEnter={() => setVisible(true)}+ onMouseLeave={() => setVisible(false)}+ onClick={() => setVisible(!visible)}+ >+ <span>{`${count.toLocaleString()} ${count === 1 ? 'person' : 'people'}`}</span>+ </button>+ </Popover>+ )+}diff --git a/products/signals/frontend/inbox/components/shell/InboxSummaryPullRequestsPopover.tsx b/products/signals/frontend/inbox/components/shell/InboxSummaryPullRequestsPopover.tsxnew file mode 100644index 000000000000..cec6f6fedc41--- /dev/null+++ b/products/signals/frontend/inbox/components/shell/InboxSummaryPullRequestsPopover.tsx@@ -0,0 +1,61 @@+import { useState } from 'react'++import { Popover } from '@posthog/lemon-ui'++import { Link } from 'lib/lemon-ui/Link'++import type { InboxSummaryPullRequestApi } from '../../../generated/api.schemas'++export function InboxSummaryPullRequestsPopover({+ pullRequests,+}: {+ pullRequests: InboxSummaryPullRequestApi[]+}): JSX.Element {+ const [visible, setVisible] = useState(false)+ const count = pullRequests.length++ return (+ <Popover+ visible={visible}+ placement="bottom-start"+ showArrow+ padded={false}+ onClickOutside={() => setVisible(false)}+ onMouseEnterInside={() => setVisible(true)}+ onMouseLeaveInside={() => setVisible(false)}+ overlay={+ <div role="dialog" aria-label="Merged pull requests" className="max-h-80 w-80 overflow-y-auto p-2">+ <p className="m-0 px-1 pb-1 text-xs font-semibold">Merged pull requests</p>+ <ul className="m-0 flex list-none flex-col gap-0.5 p-0">+ {pullRequests.map((pullRequest) => (+ <li key={`${pullRequest.repository}#${pullRequest.number}`}>+ <Link+ to={pullRequest.url}+ target="_blank"+ targetBlankIcon+ className="block truncate rounded px-1 py-0.5 text-xs"+ >+ {pullRequest.repository}#{pullRequest.number}+ </Link>+ </li>+ ))}+ </ul>+ </div>+ }+ >+ <button+ type="button"+ className="m-0 inline cursor-pointer border-0 bg-transparent p-0 font-semibold text-default underline decoration-dotted underline-offset-2 hover:text-accent"+ aria-label={`Show ${count} merged pull ${count === 1 ? 'request' : 'requests'}`}+ aria-haspopup="dialog"+ aria-expanded={visible}+ data-attr="inbox-value-summary-pull-requests"+ onMouseEnter={() => setVisible(true)}+ onMouseLeave={() => setVisible(false)}+ onClick={() => setVisible(!visible)}+ >+ <span>{`${count.toLocaleString()} ${count === 1 ? 'PR' : 'PRs'}`}</span>+ </button>+ </Popover>+ )+}diff --git a/products/signals/frontend/inbox/components/shell/InboxValueSummary.stories.tsx b/products/signals/frontend/inbox/components/shell/InboxValueSummary.stories.tsxnew file mode 100644index 000000000000..c59b1c730a11--- /dev/null+++ b/products/signals/frontend/inbox/components/shell/InboxValueSummary.stories.tsx@@ -0,0 +1,91 @@+import type { Meta, StoryObj } from '@storybook/react'++import { FEATURE_FLAGS } from 'lib/constants'++import { useStorybookMocks } from '~/mocks/browser'++import { userEvent } from 'storybook/test'++import type { InboxSummaryApi } from '../../../generated/api.schemas'+import { InboxValueSummary } from './InboxValueSummary'++const summary: InboxSummaryApi = {+ period_start: '2026-09-13T12:00:00Z',+ period_end: '2026-09-20T12:00:00Z',+ merged_pr_count: 12,+ people_count: 5,+ participation_complete: true,+ pull_requests: Array.from({ length: 12 }, (_, index) => ({+ repository: index % 3 === 0 ? 'PostHog/posthog-js' : 'PostHog/posthog',+ number: 111094 - index,+ url: `https://github.com/${index % 3 === 0 ? 'PostHog/posthog-js' : 'PostHog/posthog'}/pull/${111094 - index}`,+ })),+ people: [+ { id: 1, login: 'sam-example' },+ { id: 2, login: 'alex-example' },+ { id: 3, login: 'riley-example' },+ { id: 4, login: 'taylor-example' },+ { id: 5, login: 'jordan-example' },+ ],+}++function SummaryStory({+ response = summary,+ failed = false,+}: {+ response?: InboxSummaryApi+ failed?: boolean+}): JSX.Element {+ useStorybookMocks({+ get: { '/api/projects/:team_id/signals/inbox_summary/': () => (failed ? [503, {}] : [200, response]) },+ })+ return <InboxValueSummary visible />+}++const meta: Meta = {+ title: 'Scenes-App/Inbox/ValueSummary',+ component: InboxValueSummary,+ parameters: {+ layout: 'fullscreen',+ mockDate: '2026-09-20T12:00:00Z',+ featureFlags: [FEATURE_FLAGS.SIGNALS_INBOX_VALUE_SUMMARY],+ },+}+export default meta+type Story = StoryObj++export const Complete: Story = { render: () => <SummaryStory /> }+export const UpdatingPeople: Story = {+ render: () => (+ <SummaryStory response={{ ...summary, people_count: null, participation_complete: false, people: null }} />+ ),+}+export const NoMerges: Story = {+ render: () => (+ <SummaryStory response={{ ...summary, merged_pr_count: 0, people_count: 0, pull_requests: [], people: [] }} />+ ),+}+export const Error: Story = { render: () => <SummaryStory failed /> }+export const Narrow: Story = {+ render: () => (+ <div className="w-[520px]">+ <SummaryStory />+ </div>+ ),+}+export const PullRequestsOpen: Story = {+ render: () => <SummaryStory />,+ play: async ({ canvas }) => {+ await userEvent.hover(await canvas.findByText('12 PRs'))+ },+}+export const PeopleOpen: Story = {+ render: () => (+ <div className="w-[520px]">+ <SummaryStory />+ </div>+ ),+ play: async ({ canvas }) => {+ await userEvent.hover(await canvas.findByText('5 people'))+ },+}diff --git a/products/signals/frontend/inbox/components/shell/InboxValueSummary.test.tsx b/products/signals/frontend/inbox/components/shell/InboxValueSummary.test.tsxnew file mode 100644index 000000000000..7c9830d8b1d6--- /dev/null+++ b/products/signals/frontend/inbox/components/shell/InboxValueSummary.test.tsx@@ -0,0 +1,123 @@+/* oxlint-disable react-hooks/rules-of-hooks -- useMocks is a test helper. */+import '@testing-library/jest-dom'++import { cleanup, render, screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { captureInboxValueSummary } from '../../inboxAnalytics'+import { InboxValueSummary } from './InboxValueSummary'++jest.mock('../../inboxAnalytics', () => ({+ ...jest.requireActual('../../inboxAnalytics'),+ captureInboxValueSummary: jest.fn(),+}))++const complete = {+ period_start: '2026-09-13T12:00:00Z',+ period_end: '2026-09-20T12:00:00Z',+ merged_pr_count: 2,+ people_count: 2,+ participation_complete: true,+ pull_requests: [+ { repository: 'example/app', number: 42, url: 'https://github.com/example/app/pull/42' },+ { repository: 'example/sdk', number: 7, url: 'https://github.com/example/sdk/pull/7' },+ ],+ people: [+ { id: 10, login: 'example-merger' },+ { id: 20, login: 'example-reviewer' },+ ],+}++describe('InboxValueSummary', () => {+ let readSummary: jest.Mock++ beforeEach(() => {+ localStorage.clear()+ jest.clearAllMocks()+ readSummary = jest.fn(() => [200, complete])+ useMocks({ get: { '/api/projects/:team_id/signals/inbox_summary/': readSummary } })+ initKeaTests()+ featureFlagLogic.mount()+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.SIGNALS_INBOX_VALUE_SUMMARY]: true })+ })++ afterEach(cleanup)++ it('shows counts and records one view, then hides on dismissal', async () => {+ const { rerender } = render(<InboxValueSummary visible />)+ expect(await screen.findByText('2 PRs')).toBeInTheDocument()+ expect(screen.getByText('2 people')).toBeInTheDocument()+ expect(screen.getByText('Self-driving activity')).toBeInTheDocument()+ expect(captureInboxValueSummary).toHaveBeenCalledWith('viewed', complete)+ rerender(<InboxValueSummary visible />)+ expect(captureInboxValueSummary).toHaveBeenCalledTimes(1)+ await userEvent.click(screen.getByLabelText('Hide summary for 7 days'))+ expect(screen.queryByLabelText('Self-driving summary')).not.toBeInTheDocument()+ expect(captureInboxValueSummary).toHaveBeenLastCalledWith('dismissed', complete)+ })++ it('shows linked pull requests and people from the summary', async () => {+ render(<InboxValueSummary visible />)+ await userEvent.hover(await screen.findByText('2 PRs'))+ const pullRequest = await screen.findByText('example/app#42')+ expect(pullRequest.closest('a')).toHaveAttribute('href', 'https://github.com/example/app/pull/42')+ await userEvent.unhover(screen.getByText('2 PRs'))+ await userEvent.hover(screen.getByText('2 people'))+ expect(await screen.findByText('@example-merger')).toBeInTheDocument()+ expect(screen.getByText('@example-reviewer')).toBeInTheDocument()+ })++ it('does not mount or fetch with the flag disabled', () => {+ featureFlagLogic.actions.setFeatureFlags([], {})+ render(<InboxValueSummary visible />)+ expect(readSummary).not.toHaveBeenCalled()+ expect(screen.queryByText('Self-driving in the last 7 days')).not.toBeInTheDocument()+ })++ it('hides zero merges without a view event', async () => {+ readSummary.mockReturnValue([+ 200,+ { ...complete, merged_pr_count: 0, people_count: 0, pull_requests: [], people: [] },+ ])+ render(<InboxValueSummary visible />)+ await waitFor(() => expect(readSummary).toHaveBeenCalled())+ expect(screen.queryByLabelText('Self-driving summary')).not.toBeInTheDocument()+ expect(captureInboxValueSummary).not.toHaveBeenCalled()+ })++ it('keeps the merge count when participation is incomplete', async () => {+ readSummary.mockReturnValue([+ 200,+ { ...complete, people_count: null, participation_complete: false, people: null },+ ])+ render(<InboxValueSummary visible />)+ expect(await screen.findByText('people count updating')).toBeInTheDocument()+ expect(screen.getByText('2 PRs')).toBeInTheDocument()+ expect(screen.queryByText('0')).not.toBeInTheDocument()+ })++ it('does not record a hidden panel as viewed', async () => {+ const { rerender } = render(<InboxValueSummary visible={false} />)+ expect(readSummary).not.toHaveBeenCalled()+ expect(captureInboxValueSummary).not.toHaveBeenCalled()+ rerender(<InboxValueSummary visible />)+ expect(await screen.findByText('2 PRs')).toBeInTheDocument()+ expect(captureInboxValueSummary).toHaveBeenCalledTimes(1)+ })++ it('offers an inline retry after failure', async () => {+ readSummary.mockReturnValue([503, {}])+ render(<InboxValueSummary visible />)+ expect(await screen.findByText('Summary is not available.')).toBeInTheDocument()+ expect(captureInboxValueSummary).not.toHaveBeenCalled()+ readSummary.mockReturnValue([200, complete])+ await userEvent.click(screen.getByText('Try again'))+ expect(await screen.findByText('2 PRs')).toBeInTheDocument()+ })+})diff --git a/products/signals/frontend/inbox/components/shell/InboxValueSummary.tsx b/products/signals/frontend/inbox/components/shell/InboxValueSummary.tsxnew file mode 100644index 000000000000..e02f9e2860cd--- /dev/null+++ b/products/signals/frontend/inbox/components/shell/InboxValueSummary.tsx@@ -0,0 +1,92 @@+import { useActions, useValues } from 'kea'+import { useEffect } from 'react'++import { IconPullRequest, IconX } from '@posthog/icons'+import { LemonButton, LemonCard } from '@posthog/lemon-ui'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { teamLogic } from 'scenes/teamLogic'+import { userLogic } from 'scenes/userLogic'++import { INBOX_SUMMARY_DISMISS_MS, InboxSummaryLogicProps, inboxSummaryLogic } from '../../logics/inboxSummaryLogic'+import { InboxSummaryPeoplePopover } from './InboxSummaryPeoplePopover'+import { InboxSummaryPullRequestsPopover } from './InboxSummaryPullRequestsPopover'++function ProjectSummary(props: InboxSummaryLogicProps): JSX.Element | null {+ const logic = inboxSummaryLogic(props)+ const { summary, summaryLoading, failed, dismissed, pageVisible, hasBeenViewed } = useValues(logic)+ const { dismissSummary, refreshSummary, summaryViewed } = useActions(logic)+ const showSummary = props.visible && pageVisible && !dismissed && !failed && !!summary?.merged_pr_count++ useEffect(() => {+ if (showSummary && !hasBeenViewed) {+ summaryViewed()+ }+ }, [showSummary, hasBeenViewed, summaryViewed])++ if (!props.visible || dismissed) {+ return null+ }+ if (failed) {+ return (+ <div className="mx-6 my-2 flex items-center gap-2 text-secondary text-xs" role="status">+ Summary is not available.+ <LemonButton+ size="xsmall"+ type="tertiary"+ onClick={() => refreshSummary(true)}+ loading={summaryLoading}+ >+ Try again+ </LemonButton>+ </div>+ )+ }+ if (!summary?.merged_pr_count) {+ return null+ }++ return (+ <LemonCard+ hoverEffect={false}+ className="mx-6 my-3 flex flex-wrap items-center gap-3 p-3 shadow-none"+ data-attr="inbox-value-summary"+ >+ <section aria-label="Self-driving summary" className="contents">+ <IconPullRequest className="shrink-0 text-lg text-success" />+ <div className="min-w-0 flex-1">+ <h2 className="m-0 text-sm font-semibold">Self-driving activity</h2>+ <p className="m-0 text-xs text-secondary">+ <InboxSummaryPullRequestsPopover pullRequests={summary.pull_requests} /> merged with{' '}+ {summary.participation_complete && summary.people !== null ? (+ <InboxSummaryPeoplePopover people={summary.people} />+ ) : (+ <span className="font-medium text-secondary">people count updating</span>+ )}{' '}+ participating in the last 7 days+ </p>+ </div>+ <LemonButton+ type="tertiary"+ size="xsmall"+ icon={<IconX />}+ aria-label="Hide summary for 7 days"+ tooltip="Hide for 7 days"+ onClick={() => dismissSummary(Date.now() + INBOX_SUMMARY_DISMISS_MS)}+ />+ </section>+ </LemonCard>+ )+}++export function InboxValueSummary({ visible }: { visible: boolean }): JSX.Element | null {+ const { featureFlags } = useValues(featureFlagLogic)+ const { currentTeamId } = useValues(teamLogic)+ const { user } = useValues(userLogic)++ if (!featureFlags[FEATURE_FLAGS.SIGNALS_INBOX_VALUE_SUMMARY] || !currentTeamId || !user) {+ return null+ }+ return <ProjectSummary teamId={currentTeamId} userId={user.id} visible={visible} />+}diff --git a/products/signals/frontend/inbox/inboxAnalytics.ts b/products/signals/frontend/inbox/inboxAnalytics.tsindex bb1df9239137..3bc8d19d88f7 100644--- a/products/signals/frontend/inbox/inboxAnalytics.ts+++ b/products/signals/frontend/inbox/inboxAnalytics.ts@@ -4,6 +4,7 @@ import type { CaptureOptions } from 'posthog-js'import { dayjs } from 'lib/dayjs'import type { TaskRunStatus } from 'products/posthog_ai/frontend/types/taskTypes'+import type { InboxSummaryApi } from 'products/signals/frontend/generated/api.schemas'import type { ReportTaskPurpose } from './components/detail/artefactTypes'import type { ReportDiscussionIntent } from './inboxTaskKickoffLogic'@@ -33,6 +34,8 @@ export const INBOX_EVENTS = {WELCOME_MANUAL_SETUP_CLICKED: 'Inbox welcome manual setup clicked',INTRO_MODAL_VIEWED: 'Inbox intro modal viewed',PANEL_VIEWED: 'Inbox panel viewed',+ VALUE_SUMMARY_VIEWED: 'Inbox value summary viewed',+ VALUE_SUMMARY_DISMISSED: 'Inbox value summary dismissed',PANEL_LOAD_TIMED_OUT: 'Inbox panel load timed out',QUERY_CHANGED: 'Inbox query changed',REPORTS_IMPRESSED: 'Inbox reports impressed',@@ -76,6 +79,14 @@ export const INBOX_EVENTS = {type InboxEvent = (typeof INBOX_EVENTS)[keyof typeof INBOX_EVENTS]+export function captureInboxValueSummary(action: 'viewed' | 'dismissed', summary: InboxSummaryApi): void {+ captureInboxEvent(action === 'viewed' ? INBOX_EVENTS.VALUE_SUMMARY_VIEWED : INBOX_EVENTS.VALUE_SUMMARY_DISMISSED, {+ merged_pr_count: summary.merged_pr_count,+ people_count: summary.people_count,+ participation_complete: summary.participation_complete,+ })+}+/*** Action surface an `Inbox report action` fired from. `context_menu` is the right-click menu on a list row.* `today` is a report page on the Today homepage.diff --git a/products/signals/frontend/inbox/logics/inboxSummaryLogic.test.ts b/products/signals/frontend/inbox/logics/inboxSummaryLogic.test.tsnew file mode 100644index 000000000000..b817f04d8bdf--- /dev/null+++ b/products/signals/frontend/inbox/logics/inboxSummaryLogic.test.ts@@ -0,0 +1,119 @@+/* oxlint-disable react-hooks/rules-of-hooks -- useMocks is a test helper. */+import { expectLogic } from 'kea-test-utils'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { INBOX_SUMMARY_DISMISS_MS, INBOX_SUMMARY_FRESH_MS, inboxSummaryLogic } from './inboxSummaryLogic'++const summary = {+ period_start: '2026-09-13T12:00:00Z',+ period_end: '2026-09-20T12:00:00Z',+ merged_pr_count: 4,+ people_count: 3,+ participation_complete: true,+}++describe('inboxSummaryLogic', () => {+ let logic: ReturnType<typeof inboxSummaryLogic.build>+ let readSummary: jest.Mock+ let now: number++ const mountLogic = (): void => {+ logic.mount()+ }++ beforeEach(() => {+ now = Date.parse(summary.period_end)+ jest.spyOn(Date, 'now').mockImplementation(() => now)+ localStorage.clear()+ readSummary = jest.fn(() => [200, summary])+ useMocks({ get: { '/api/projects/:team_id/signals/inbox_summary/': readSummary } })+ initKeaTests()+ logic = inboxSummaryLogic({ teamId: 2, userId: 10, visible: true })+ })++ afterEach(() => {+ logic.unmount()+ jest.restoreAllMocks()+ })++ it('loads project counts and only refreshes stale results on return', async () => {+ await expectLogic(logic, mountLogic).toFinishAllListeners().toMatchValues({ summary })+ expect(readSummary).toHaveBeenCalledTimes(1)+ await expectLogic(logic, () => logic.actions.refreshSummary()).toFinishAllListeners()+ expect(readSummary).toHaveBeenCalledTimes(1)+ now += INBOX_SUMMARY_FRESH_MS+ await expectLogic(logic, () => {+ window.dispatchEvent(new Event('focus'))+ }).toFinishAllListeners()+ expect(readSummary).toHaveBeenCalledTimes(2)+ })++ it('does not fetch while a detail view hides the panel', async () => {+ logic = inboxSummaryLogic({ teamId: 2, userId: 10, visible: false })+ await expectLogic(logic, mountLogic).toFinishAllListeners()+ expect(readSummary).not.toHaveBeenCalled()+ await expectLogic(logic, () => {+ inboxSummaryLogic({ teamId: 2, userId: 10, visible: true })+ }).toFinishAllListeners()+ expect(readSummary).toHaveBeenCalledTimes(1)+ })++ it('persists dismissal for seven days and resumes on return', async () => {+ await expectLogic(logic, mountLogic).toFinishAllListeners()+ logic.actions.dismissSummary(now + INBOX_SUMMARY_DISMISS_MS)+ expect(logic.values.dismissed).toBe(true)+ logic.unmount()+ logic = inboxSummaryLogic({ teamId: 2, userId: 10, visible: true })+ await expectLogic(logic, mountLogic).toFinishAllListeners()+ expect(logic.values.dismissed).toBe(true)+ expect(readSummary).toHaveBeenCalledTimes(1)+ now += INBOX_SUMMARY_DISMISS_MS+ await expectLogic(logic, () => logic.actions.refreshSummary()).toFinishAllListeners()+ expect(logic.values.dismissed).toBe(false)+ expect(readSummary).toHaveBeenCalledTimes(2)+ })++ it.each([+ { teamId: 3, userId: 10 },+ { teamId: 2, userId: 20 },+ ])('does not share dismissal with $teamId / $userId', async (identity) => {+ await expectLogic(logic, mountLogic).toFinishAllListeners()+ logic.actions.dismissSummary(now + INBOX_SUMMARY_DISMISS_MS)+ logic.unmount()+ logic = inboxSummaryLogic({ ...identity, visible: true })+ await expectLogic(logic, mountLogic).toFinishAllListeners()+ expect(logic.values.dismissed).toBe(false)+ expect(readSummary).toHaveBeenCalledTimes(2)+ })++ it('keeps unknown participation and supports retry after a failed request', async () => {+ readSummary.mockReturnValue([503, { detail: 'Not available' }])+ await expectLogic(logic, mountLogic).toFinishAllListeners().toMatchValues({ failed: true, summary: null })+ const incomplete = { ...summary, people_count: null, participation_complete: false }+ readSummary.mockReturnValue([200, incomplete])+ await expectLogic(logic, () => logic.actions.refreshSummary(true))+ .toFinishAllListeners()+ .toMatchValues({+ failed: false,+ summary: incomplete,+ })+ })++ it('retries on return after a failed refresh', async () => {+ await expectLogic(logic, mountLogic).toFinishAllListeners().toMatchValues({ summary })+ readSummary.mockReturnValue([503, { detail: 'Not available' }])+ await expectLogic(logic, () => logic.actions.refreshSummary(true))+ .toFinishAllListeners()+ .toMatchValues({ failed: true, loadedAt: 0 })+ readSummary.mockReturnValue([200, summary])++ await expectLogic(logic, () => {+ window.dispatchEvent(new Event('focus'))+ })+ .toFinishAllListeners()+ .toMatchValues({ failed: false, summary })+ expect(readSummary).toHaveBeenCalledTimes(3)+ })+})diff --git a/products/signals/frontend/inbox/logics/inboxSummaryLogic.ts b/products/signals/frontend/inbox/logics/inboxSummaryLogic.tsnew file mode 100644index 000000000000..6855fe6f6902--- /dev/null+++ b/products/signals/frontend/inbox/logics/inboxSummaryLogic.ts@@ -0,0 +1,204 @@+import {+ MakeLogicType,+ actions,+ afterMount,+ kea,+ key,+ listeners,+ path,+ props,+ propsChanged,+ reducers,+ selectors,+} from 'kea'+import { loaders } from 'kea-loaders'++import * as api from 'products/signals/frontend/generated/api'+import type { InboxSummaryApi } from 'products/signals/frontend/generated/api.schemas'++import { captureInboxValueSummary } from '../inboxAnalytics'++export const INBOX_SUMMARY_DISMISS_MS = 7 * 24 * 60 * 60 * 1000+export const INBOX_SUMMARY_FRESH_MS = 5 * 60 * 1000++export interface InboxSummaryLogicProps {+ teamId: number+ userId: number+ visible: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface inboxSummaryLogicValues {+ dismissed: boolean+ dismissedUntil: number+ failed: boolean+ hasBeenViewed: boolean+ loadedAt: number+ now: number+ pageVisible: boolean+ summary: InboxSummaryApi | null+ summaryLoading: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface inboxSummaryLogicActions {+ armDismissalExpiry: () => {+ value: true+ }+ dismissSummary: (until: number) => {+ until: number+ }+ loadInboxSummary: (_: void) => void+ loadInboxSummaryFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadInboxSummarySuccess: (+ summary: InboxSummaryApi,+ payload?: void+ ) => {+ summary: InboxSummaryApi+ payload?: void+ }+ refreshSummary: (force?: boolean) => {+ force: boolean+ }+ summaryViewed: () => {+ value: true+ }+ updateClock: (+ now: number,+ pageVisible: boolean+ ) => {+ now: number+ pageVisible: boolean+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface inboxSummaryLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ dismissed: (dismissedUntil: number, now: number) => boolean+ }+}++export type inboxSummaryLogicType = MakeLogicType<+ inboxSummaryLogicValues,+ inboxSummaryLogicActions,+ InboxSummaryLogicProps,+ inboxSummaryLogicMeta+>++export const inboxSummaryLogic = kea<inboxSummaryLogicType>([+ props({} as InboxSummaryLogicProps),+ key(({ teamId, userId }) => `${userId}:${teamId}`),+ path((key) => ['products', 'signals', 'inbox', 'inboxSummaryLogic', key]),+ actions({+ refreshSummary: (force: boolean = false) => ({ force }),+ updateClock: (now: number, pageVisible: boolean) => ({ now, pageVisible }),+ dismissSummary: (until: number) => ({ until }),+ summaryViewed: true,+ armDismissalExpiry: true,+ }),+ loaders(({ props }) => ({+ summary: [+ null as InboxSummaryApi | null,+ {+ loadInboxSummary: async (_: void, breakpoint) => {+ const summary = await api.signalsInboxSummaryList(String(props.teamId))+ breakpoint()+ return summary+ },+ },+ ],+ })),+ reducers({+ dismissedUntil: [0, { persist: true }, { dismissSummary: (_, { until }) => until }],+ now: [Date.now(), { updateClock: (_, { now }) => now }],+ pageVisible: [!document.hidden, { updateClock: (_, { pageVisible }) => pageVisible }],+ loadedAt: [+ 0,+ {+ loadInboxSummarySuccess: () => Date.now(),+ loadInboxSummaryFailure: () => 0,+ },+ ],+ failed: [false, { loadInboxSummary: () => false, loadInboxSummaryFailure: () => true }],+ hasBeenViewed: [false, { summaryViewed: () => true }],+ }),+ selectors({+ dismissed: [+ (s) => [s.dismissedUntil, s.now],+ (until: number, now: number): boolean => Number.isFinite(until) && until > now,+ ],+ }),+ listeners(({ values, actions, props, cache }) => ({+ refreshSummary: ({ force }) => {+ actions.updateClock(Date.now(), !document.hidden)+ if (+ props.visible &&+ values.pageVisible &&+ !values.dismissed &&+ !values.summaryLoading &&+ (force || Date.now() - values.loadedAt >= INBOX_SUMMARY_FRESH_MS)+ ) {+ actions.loadInboxSummary()+ }+ },+ dismissSummary: () => {+ if (values.summary) {+ captureInboxValueSummary('dismissed', values.summary)+ }+ actions.armDismissalExpiry()+ },+ summaryViewed: () => {+ if (values.summary) {+ captureInboxValueSummary('viewed', values.summary)+ }+ },+ armDismissalExpiry: () => {+ cache.disposables.dispose('dismissal-expiry')+ if (Number.isFinite(values.dismissedUntil) && values.dismissedUntil > Date.now()) {+ cache.disposables.add(() => {+ const timeout = window.setTimeout(+ () => actions.refreshSummary(),+ Math.max(0, values.dismissedUntil - Date.now())+ )+ return () => window.clearTimeout(timeout)+ }, 'dismissal-expiry')+ }+ },+ })),+ afterMount(({ actions, cache }) => {+ cache.disposables.add(+ () => {+ actions.refreshSummary()+ const refresh = (): void => actions.refreshSummary()+ const visibilityChanged = (): void => {+ actions.updateClock(Date.now(), !document.hidden)+ if (!document.hidden) {+ actions.refreshSummary()+ }+ }+ window.addEventListener('focus', refresh)+ document.addEventListener('visibilitychange', visibilityChanged)+ return () => {+ window.removeEventListener('focus', refresh)+ document.removeEventListener('visibilitychange', visibilityChanged)+ }+ },+ 'page-visibility',+ { pauseOnPageHidden: false }+ )+ actions.armDismissalExpiry()+ }),+ propsChanged(({ actions, props }, oldProps) => {+ if (props.visible && !oldProps.visible) {+ actions.refreshSummary()+ }+ }),+])diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex e688145f5124..d0953945589d 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -62,6 +62,7 @@ from posthog.models.oauth import OAuthAccessToken, OAuthRefreshTokenfrom posthog.temporal.oauth import CONTEXT_LAYER_INTERNAL_SCOPEfrom posthog.utils import absolute_uri+from products.access_control.backend.facade.user_access_control import UserAccessControlfrom products.cdp.backend.facade import api as cdp_facadefrom products.posthog_ai.backend.task_ownership import (detach_conversations_for_task_handoff,@@ -168,7 +169,9 @@ from products.tasks.backend.models import (TaskWorkflowDispatch,)from products.tasks.backend.pr_urls import (+ canonical_github_pull_request_url,merge_pr_output,+ normalize_verified_pull_request_urls,read_head_branches,read_pr_urls as read_pr_urls,)@@ -301,6 +304,8 @@ __all__ = ["filter_uncovered_workflow_dispatch_run_ids","maintain_workflow_dispatch_outbox","get_task_detail",+ "task_access_scope",+ "normalize_verified_pull_request_urls_batch","get_task_id_for_run","get_task_run","get_task_run_session",@@ -1098,13 +1103,49 @@ def get_task_id_for_run(run_id: str | UUID, team_id: int) -> UUID | None:return TaskRun.objects.filter(id=run_id, team_id=team_id).values_list("task_id", flat=True).first()+def task_access_scope(*, team_id: int, user: User) -> contracts.TaskAccessScope:+ team = Team.objects.get(id=team_id)+ access = UserAccessControl(user=user, team=team)+ return contracts.TaskAccessScope(+ user_id=user.id,+ has_resource_access=access.has_resource_access("task"),+ allowed_ids=access.allowlisted_resource_ids_by_scope.get("task", frozenset()),+ blocked_ids=access.blocked_resource_ids_by_scope.get("task", frozenset()),+ )+++def normalize_verified_pull_request_urls_batch(+ *, team_id: int, after: UUID | None = None, limit: int = 1000+) -> UUID | None:+ rows = TaskRun.objects.filter(team_id=team_id, state__has_key="verified_pr_urls").order_by("id")+ if after is not None:+ rows = rows.filter(id__gt=after)+ batch = list(rows.values_list("id", "state")[:limit])+ for run_id, state in batch:+ verified = state.get("verified_pr_urls") if isinstance(state, dict) else None+ if normalize_verified_pull_request_urls(verified) == verified:+ continue++ def normalize(latest_state: dict[str, Any]) -> None:+ latest_state["verified_pr_urls"] = normalize_verified_pull_request_urls(+ latest_state.get("verified_pr_urls")+ )++ TaskRun.mutate_state_atomic(run_id, normalize)+ return batch[-1][0] if len(batch) == limit else None++def is_verified_task_pr_url(*, task_id: str | UUID, team_id: int, pr_url: str) -> bool:"""Whether the GitHub webhook confirmed that a run of this task opened the pull request.A run's `output.pr_url` is writable through the API. `verified_pr_urls` is server-owned, so acaller that edits the pull request checks this before it trusts the URL."""- return TaskRun.objects.filter(task_id=task_id, team_id=team_id, state__verified_pr_urls__contains=[pr_url]).exists()+ verified_url = canonical_github_pull_request_url(pr_url)+ verified_filter = Q(state__verified_pr_urls__contains=[pr_url])+ if verified_url is not None:+ verified_filter |= Q(state__verified_pr_urls__contains=[verified_url])+ return TaskRun.objects.filter(verified_filter, task_id=task_id, team_id=team_id).exists()def task_exists(task_id: str | UUID, team_id: int) -> bool:diff --git a/products/tasks/backend/facade/contracts.py b/products/tasks/backend/facade/contracts.pyindex b39fd5287b68..155bb5aa3202 100644--- a/products/tasks/backend/facade/contracts.py+++ b/products/tasks/backend/facade/contracts.py@@ -55,6 +55,16 @@ class TaskDTO:slug: str = ""+@dataclass(frozen=True, kw_only=True)+class TaskAccessScope:+ """Task IDs a user can or cannot access through channel visibility rules."""++ user_id: int+ has_resource_access: bool+ allowed_ids: frozenset[str]+ blocked_ids: frozenset[str]++@dataclass(frozen=True, kw_only=True)class AgentTaskRunDTO:"""Identity and workflow handle for a newly dispatched agent task."""diff --git a/products/tasks/backend/logic/services/pr_reconciliation.py b/products/tasks/backend/logic/services/pr_reconciliation.pyindex bfc859d44c78..69785f170292 100644--- a/products/tasks/backend/logic/services/pr_reconciliation.py+++ b/products/tasks/backend/logic/services/pr_reconciliation.py@@ -19,7 +19,12 @@ from posthog.models.user_integration import UserGitHubIntegrationfrom products.signals.backend.facade.github import reconcile_pull_request_statefrom products.tasks.backend.models import Task, TaskRun-from products.tasks.backend.pr_urls import read_head_branches, read_pr_urls+from products.tasks.backend.pr_urls import (+ canonical_github_pull_request_url,+ normalize_verified_pull_request_urls,+ read_head_branches,+ read_pr_urls,+)from products.tasks.backend.webhooks import _run_repository_filter, _task_run_scope_team_ids, find_task_runlogger = structlog.get_logger(__name__)@@ -66,7 +71,8 @@ class PullRequestReconciler:)state = run.state if isinstance(run.state, dict) else {}- verified = state.get("verified_pr_urls") or []+ raw_verified = state.get("verified_pr_urls")+ verified = raw_verified if isinstance(raw_verified, list) else []metadata_changed = run.branch != previous_branch or read_head_branches(run.output) != read_head_branches(previous_output)@@ -95,11 +101,15 @@ class PullRequestReconciler:def _eligible(self, run: TaskRun) -> bool:state = run.state if isinstance(run.state, dict) else {}+ raw_verified = state.get("verified_pr_urls")+ verified = raw_verified if isinstance(raw_verified, list) else []+ canonical_url = canonical_github_pull_request_url(self.pr_url)return (not run.task.deletedand run.task.origin_product != Task.OriginProduct.REVIEW_HOGand self.pr_url in read_pr_urls(run.output)- and self.pr_url not in (state.get("verified_pr_urls") or [])+ and self.pr_url not in verified+ and (canonical_url is None or canonical_url not in verified))@staticmethod@@ -191,7 +201,9 @@ class PullRequestReconciler:verified = state.get("verified_pr_urls")locked.state = {**state,- "verified_pr_urls": [*(verified if isinstance(verified, list) else []), self.pr_url],+ "verified_pr_urls": normalize_verified_pull_request_urls(+ [*(verified if isinstance(verified, list) else []), self.pr_url]+ ),}output = locked.output if isinstance(locked.output, dict) else {}if output.get("pr_url") == self.pr_url:diff --git a/products/tasks/backend/pr_urls.py b/products/tasks/backend/pr_urls.pyindex 8ead88347405..69a63c15c3ff 100644--- a/products/tasks/backend/pr_urls.py+++ b/products/tasks/backend/pr_urls.py@@ -1,3 +1,23 @@+from posthog.models.github_integration_base import GitHubIntegrationBase+++def canonical_github_pull_request_url(url: str) -> str | None:+ parsed = GitHubIntegrationBase.parse_pull_request_url(url)+ return f"https://github.com/{parsed.repository.lower()}/pull/{parsed.number}" if parsed else None+++def normalize_verified_pull_request_urls(value: object) -> list[object]:+ urls = value if isinstance(value, list) else []+ normalized: list[object] = []+ for url in urls:+ if url not in normalized:+ normalized.append(url)+ canonical = canonical_github_pull_request_url(url) if isinstance(url, str) else None+ if canonical is not None and canonical not in normalized:+ normalized.append(canonical)+ return normalized++def read_pr_urls(output: object) -> list[str]:if not isinstance(output, dict):return []diff --git a/products/tasks/backend/webhooks.py b/products/tasks/backend/webhooks.pyindex 4a6ceb089a35..d02f303b94ff 100644--- a/products/tasks/backend/webhooks.py+++ b/products/tasks/backend/webhooks.py@@ -20,7 +20,12 @@ from products.tasks.backend.facade.api import post_pr_created_thread_update, sigfrom products.tasks.backend.facade.cancellation import cancel_task_runfrom products.tasks.backend.metrics import observe_github_webhook_task_run_lookupfrom products.tasks.backend.models import Task, TaskRun-from products.tasks.backend.pr_urls import merge_pr_output, read_pr_urls+from products.tasks.backend.pr_urls import (+ canonical_github_pull_request_url,+ merge_pr_output,+ normalize_verified_pull_request_urls,+ read_pr_urls,+)from products.tasks.backend.prompts import WIZARD_HEAD_BRANCH_PREFIXlogger = structlog.get_logger(__name__)@@ -73,7 +78,11 @@ def find_task_run(# original and its live resume can both claim the same PR URL. Scope to the# webhook's repo and prefer non-terminal runs so merge handling lands on the# run that can still act on it.- runs = candidates.filter(state__verified_pr_urls__contains=[pr_url])+ verified_url = canonical_github_pull_request_url(pr_url)+ verified_filter = Q(state__verified_pr_urls__contains=[pr_url])+ if verified_url is not None:+ verified_filter |= Q(state__verified_pr_urls__contains=[verified_url])+ runs = candidates.filter(verified_filter)if repository:runs = runs.filter(_run_repository_filter(repository))# Declared type keeps mypy happy: the annotated queryset yields an AnnotatedWith@@ -398,12 +407,12 @@ def _append_run_pr_url(task_run: TaskRun, pr_url: str) -> bool:locked = TaskRun.objects.select_for_update().get(id=task_run.id)state = locked.state if isinstance(locked.state, dict) else {}existing_verified = state.get("verified_pr_urls")- verified_pr_urls = list(- dict.fromkeys([*(existing_verified if isinstance(existing_verified, list) else []), pr_url])+ verified_pr_urls = normalize_verified_pull_request_urls(+ [*(existing_verified if isinstance(existing_verified, list) else []), pr_url])locked.state = {**state, "verified_pr_urls": verified_pr_urls}if pr_url in read_pr_urls(locked.output):- if not isinstance(existing_verified, list) or pr_url not in existing_verified:+ if verified_pr_urls != existing_verified:# Restart report linking when its earlier attempt ran before verification.locked.save(update_fields=["state", "output", "updated_at"])task_run.state = locked.statediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex fcde5e88a317..2e5246b553cc 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -59793,6 +59793,45 @@ export namespace Schemas {working: ImpactWorking | null;}+ export interface InboxSummaryPullRequest {+ /** GitHub repository in owner/name format. */+ repository: string;+ /** GitHub pull request number. */+ number: number;+ /** URL of the GitHub pull request. */+ url: string;+ }++ export interface InboxSummaryPerson {+ /** Stable GitHub user ID. */+ id: number;+ /** Current GitHub login from the participant snapshot. */+ login: string;+ }++ export interface InboxSummary {+ /** Inclusive start of the rolling seven-day period. */+ period_start: string;+ /** Exclusive end of the rolling seven-day period. */+ period_end: string;+ /** Distinct verified Self-driving implementation PRs merged in the period. */+ merged_pr_count: number;+ /**+ * Distinct human approvers and mergers, or null while incomplete.+ * @nullable+ */+ people_count: number | null;+ /** Whether every counted PR has a complete participant snapshot. */+ participation_complete: boolean;+ /** Verified Self-driving implementation PRs merged in the period. */+ pull_requests: InboxSummaryPullRequest[];+ /**+ * Distinct human approvers and mergers, or null while participation is incomplete.+ * @nullable+ */+ people: InboxSummaryPerson[] | null;+ }+/*** Coarse type per candidate, keyed by column name: datetime, date, integer, decimal, float, string, or uuid. A candidate with no entry has a type the check could not determine.*/