: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 CI status on the inbox PR pill (#93921)
posthog[bot]792b18b4db51
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex ee44a792a211..08ec0c3ea37f 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -2044,6 +2044,10 @@ snapshots:hash: v1.k794b7964.9a607e1c8b67aa4caf736f532eae8f04172a08b1519a5b233caed383cd61ac2e.oJJ1rz584k526jS3YRjmGoRSSlONVnNRC_gh0BpAWDwcomponents-sharing--recording-sharing-licensed--light:hash: v1.k794b7964.e5e8a1004d1628fd8a6a6f29a9071a59f3664ca9535cc757db079dde1241cecb.52undskkRbk3x7FpaxFiwDs9NNQWavdegSSi5D8JiRI+ components-signal-report-pr-badge--states--dark:+ hash: v1.k794b7964.abb25883b468a3ab092d289a9514e4fdd40ef6190e710d94ba8d63f36e38f8ad.NB2aqbsGNbvB7d1Qe5Hqh1xz2g6vS1RE-O6LY7xurks+ components-signal-report-pr-badge--states--light:+ hash: v1.k794b7964.6da8eed2f535185fbd38dfb732c55060a6567cd7d4795aa159069564b293272c.4i60xTjiWcEymIBaQj7-GBN1y14k4pqUDDymGPm5xa4components-skillpicker--default--dark:hash: v1.k794b7964.42e480d1854fa4e855c514aa6cb4e0adebde88d01cccd1b802b6a2acba0ccfd3.zWHBN45jGiaWgIUoC6ZoTFd9RLQ9LxAZ5x5szvvO2aEcomponents-skillpicker--default--light:diff --git a/frontend/src/initKea.ts b/frontend/src/initKea.tsindex 606fcabcd3f8..229d2c50ba57 100644--- a/frontend/src/initKea.ts+++ b/frontend/src/initKea.ts@@ -54,6 +54,7 @@ const ERROR_FILTER_ALLOW_LIST = ['loadInstallRequests', // Polled in the background on Settings → Integrations; the banner just stays hidden'loadPrChecks', // Polled in the Inbox report detail; the CI checks section renders its own error state'loadPrComments', // The Inbox report detail's PR comments section renders its own error state+ 'loadCiStatuses', // Decorative CI glyphs polled by the Inbox list; a failure just leaves the pill without one'loadMonitoringSnapshot', // The managed warehouse Monitoring tab renders its own retry state'loadMonitoringSeries', // The managed warehouse Monitoring tab renders its own partial/error state'loadInstrumentationChecklist', // AI observability hides its checklist entirely rather than accusing a project on data it could not readdiff --git a/frontend/src/lib/signals/SignalReportPrBadge.stories.tsx b/frontend/src/lib/signals/SignalReportPrBadge.stories.tsxnew file mode 100644index 000000000000..23d83881079e--- /dev/null+++ b/frontend/src/lib/signals/SignalReportPrBadge.stories.tsx@@ -0,0 +1,40 @@+import type { Meta, StoryObj } from '@storybook/react'++import type { PullRequestCiStatusEnumApi } from 'products/signals/frontend/generated/api.schemas'++import type { PrBadgeState } from './prState'+import { PrBadge } from './SignalReportPrBadge'++const meta: Meta<typeof PrBadge> = {+ title: 'Components/Signal report PR badge',+ component: PrBadge,+}+export default meta++type Story = StoryObj<typeof PrBadge>++const LIFECYCLE: PrBadgeState[] = ['open', 'merged', 'closed']+const CI_STATUSES: (PullRequestCiStatusEnumApi | undefined)[] = [undefined, 'passing', 'failing', 'pending', 'none']++// Every pill a report list can show. Only an open pull request carries a CI glyph, so the merged and+// closed rows are expected to look the same across the CI columns.+export const States: Story = {+ render: () => (+ <div className="flex flex-col gap-3 p-4">+ {LIFECYCLE.map((state) => (+ <div key={state} className="flex items-center gap-3">+ <span className="w-16 text-xs text-secondary">{state}</span>+ {CI_STATUSES.map((ciStatus) => (+ <PrBadge+ key={ciStatus ?? 'unknown'}+ prNumber="1234"+ prUrl="https://github.com/PostHog/posthog/pull/1234"+ state={state}+ ciStatus={ciStatus}+ />+ ))}+ </div>+ ))}+ </div>+ ),+}diff --git a/frontend/src/lib/signals/SignalReportPrBadge.tsx b/frontend/src/lib/signals/SignalReportPrBadge.tsxindex fddd16a0535c..dd3543a79f28 100644--- a/frontend/src/lib/signals/SignalReportPrBadge.tsx+++ b/frontend/src/lib/signals/SignalReportPrBadge.tsx@@ -1,9 +1,11 @@-import { IconPullRequest, type IconProps } from '@posthog/icons'+import { IconCheckCircle, IconPullRequest, IconSpinner, IconWarning, type IconProps } from '@posthog/icons'import { Link, Tooltip } from '@posthog/lemon-ui'import { cn } from 'lib/utils/css-classes'-import { PR_BADGE_STATE, type PrBadgeState } from './prState'+import type { PullRequestCiStatusEnumApi } from 'products/signals/frontend/generated/api.schemas'++import { PR_BADGE_STATE, PR_CI_GLYPH, prCiGlyphStatus, type PrBadgeState, type PrCiGlyphStatus } from './prState'function IconGitMerge(props: IconProps): JSX.Element {return (@@ -21,18 +23,41 @@ function IconGitPullRequestClosed(props: IconProps): JSX.Element {)}+/**+ * The CI state of an open pull request, as one small glyph. Rendered nothing when the state says+ * nothing: a head commit with no checks, and a status GitHub has not answered with.+ */+function PrCiGlyph({ status }: { status: PrCiGlyphStatus | null }): JSX.Element | null {+ if (!status) {+ return null+ }+ const className = cn('size-3', PR_CI_GLYPH[status].className)+ if (status === 'failing') {+ return <IconWarning className={className} />+ }+ if (status === 'pending') {+ return <IconSpinner className={cn(className, 'animate-spin motion-reduce:animate-none')} />+ }+ return <IconCheckCircle className={className} />+}+export function PrBadge({prNumber,prUrl,state,+ ciStatus,}: {prNumber: stringprUrl?: string | nullstate: PrBadgeState+ /** CI rollup of the pull request, when it is known. Only an open pull request shows one. */+ ciStatus?: PullRequestCiStatusEnumApi | null}): JSX.Element {const { label, className, hoverClassName } = PR_BADGE_STATE[state]const StateIcon =state === 'merged' ? IconGitMerge : state === 'closed' ? IconGitPullRequestClosed : IconPullRequest+ const glyphStatus = prCiGlyphStatus(state, ciStatus)+ const description = glyphStatus ? `${label}, ${PR_CI_GLYPH[glyphStatus].label}` : labelconst badge = (<spanclassName={cn(@@ -43,21 +68,22 @@ export function PrBadge({><StateIcon className="size-3" /><span className="font-mono tabular-nums">#{prNumber}</span>+ <PrCiGlyph status={glyphStatus} /></span>)if (!prUrl) {- return <Tooltip title={`Pull request #${prNumber} (${label})`}>{badge}</Tooltip>+ return <Tooltip title={`Pull request #${prNumber} (${description})`}>{badge}</Tooltip>}return (- <Tooltip title={`Open pull request #${prNumber} (${label}) on GitHub`}>+ <Tooltip title={`Open pull request #${prNumber} (${description}) on GitHub`}><Linkto={prUrl}target="_blank"disableClientSideRoutingonClick={(e) => e.stopPropagation()}- aria-label={`Open pull request #${prNumber} (${label}) on GitHub`}+ aria-label={`Open pull request #${prNumber} (${description}) on GitHub`}className="no-underline">{badge}diff --git a/frontend/src/lib/signals/prState.test.ts b/frontend/src/lib/signals/prState.test.tsnew file mode 100644index 000000000000..292cc602d35d--- /dev/null+++ b/frontend/src/lib/signals/prState.test.ts@@ -0,0 +1,28 @@+import { SignalReportStatus } from 'products/signals/frontend/inbox/types'++import { derivePrState, prCiGlyphStatus } from './prState'++describe('prState', () => {+ describe('prCiGlyphStatus', () => {+ // A glyph is a claim about work a reader can still act on. Claiming it for a landed pull+ // request, or claiming green when nothing answered, is worse than saying nothing.+ it.each([+ ['a failing open pull request', 'open', 'failing', 'failing'],+ ['a passing open pull request', 'open', 'passing', 'passing'],+ ['an open pull request mid-build', 'open', 'pending', 'pending'],+ ['a head commit with no checks', 'open', 'none', null],+ ['a status nothing has answered with', 'open', undefined, null],+ ['a merged pull request', 'merged', 'failing', null],+ ['a closed pull request', 'closed', 'failing', null],+ ] as const)('shows %s as %s', (_case, state, ciStatus, expected) => {+ expect(prCiGlyphStatus(state, ciStatus)).toBe(expected)+ })++ it('never glyphs a pull request the report has moved past', () => {+ // The two derivations have to agree: a resolved report's pill reads "closed", so the CI+ // state its report still carries must not paint it.+ const state = derivePrState(SignalReportStatus.RESOLVED, false)+ expect(prCiGlyphStatus(state, 'failing')).toBeNull()+ })+ })+})diff --git a/frontend/src/lib/signals/prState.ts b/frontend/src/lib/signals/prState.tsindex 36e1ef1f0769..a2fef3384586 100644--- a/frontend/src/lib/signals/prState.ts+++ b/frontend/src/lib/signals/prState.ts@@ -1,3 +1,4 @@+import type { PullRequestCiStatusEnumApi } from 'products/signals/frontend/generated/api.schemas'import { SignalReportStatus } from 'products/signals/frontend/inbox/types'export const PR_BADGE_STATE = {@@ -40,3 +41,28 @@ export function derivePrState(status: SignalReportStatus | string, prMerged: boo}return 'open'}++/**+ * The CI states the pill says something about, and the words and color each gets. A head commit with+ * no checks (`none`) and a status GitHub could not answer for both mean there is nothing to report,+ * so neither draws a glyph. An absent glyph never claims a pull request is green.+ */+export const PR_CI_GLYPH = {+ passing: { label: 'checks passing', className: 'text-success' },+ failing: { label: 'checks failing', className: 'text-danger' },+ pending: { label: 'checks running', className: 'text-warning' },+}++export type PrCiGlyphStatus = keyof typeof PR_CI_GLYPH++/** The glyph an open pull request's CI state earns, or null when there is nothing to show. */+export function prCiGlyphStatus(+ state: PrBadgeState,+ ciStatus?: PullRequestCiStatusEnumApi | null+): PrCiGlyphStatus | null {+ // Only an open pull request has CI a reader can act on; on a merged or closed one it is history.+ if (state !== 'open' || !ciStatus || !(ciStatus in PR_CI_GLYPH)) {+ return null+ }+ return ciStatus as PrCiGlyphStatus+}diff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.pyindex c8fba6b024e5..5ec9edd6ff9e 100644--- a/posthog/models/github_integration_base.py+++ b/posthog/models/github_integration_base.py@@ -1603,6 +1603,60 @@ class GitHubIntegrationBase:"updated_at": pr.get("updatedAt"),}+ # Pull requests per aliased CI-rollup query. Each alias reads one PR and the check rollup of its+ # head commit, so a batch this size stays well inside GitHub's GraphQL node limit. A longer list+ # is split across several calls, and a failure in any of them raises without the batches that+ # already landed, so a caller that must keep those feeds this method one batch at a time.+ PR_CI_STATUS_BATCH_SIZE = 25++ def get_pull_request_ci_statuses(self, references: Iterable[PullRequestRef]) -> dict[PullRequestRef, str]:+ """The coarse CI rollup of many pull requests, keyed by reference.++ Values use the same vocabulary as :meth:`get_pull_request_snapshot`'s ``ci_status``+ (``passing`` / ``failing`` / ``pending`` / ``none``). One GraphQL call covers up to+ ``PR_CI_STATUS_BATCH_SIZE`` pull requests, which is what makes this affordable for a list of+ pull requests rather than a single one.++ A pull request this installation cannot read is left out of the result instead of raising, so+ one unreachable repository still lets the rest of the batch resolve. Rate limits raise+ :class:`GitHubRateLimitError`, a denied egress budget raises ``GitHubEgressBudgetExhausted``,+ and other failures raise ``GitHubIntegrationError``. Callers own the back-off for all three.+ """+ unique = list(dict.fromkeys(references))+ statuses: dict[PullRequestRef, str] = {}+ for start in range(0, len(unique), self.PR_CI_STATUS_BATCH_SIZE):+ batch = unique[start : start + self.PR_CI_STATUS_BATCH_SIZE]+ declarations = ", ".join(+ f"$owner{i}: String!, $repo{i}: String!, $number{i}: Int!" for i in range(len(batch))+ )+ selections = "\n".join(+ f" pr{i}: repository(owner: $owner{i}, name: $repo{i}) {{"+ f" pullRequest(number: $number{i}) {{ commits(last: 1) {{ nodes {{ commit {{"+ f" statusCheckRollup {{ state }} }} }} }} }} }}"+ for i in range(len(batch))+ )+ variables: dict[str, Any] = {}+ for i, reference in enumerate(batch):+ variables[f"owner{i}"] = reference.owner+ variables[f"repo{i}"] = reference.repo+ variables[f"number{i}"] = reference.number++ data = self._gh_graphql(+ f"query({declarations}) {{\n{selections}\n}}",+ variables,+ endpoint="/graphql:pullRequestCiStatuses",+ )+ for i, reference in enumerate(batch):+ pull_request = ((data or {}).get(f"pr{i}") or {}).get("pullRequest")+ if not pull_request:+ continue+ rollup_nodes = ((pull_request.get("commits") or {}).get("nodes")) or []+ rollup_state = None+ if rollup_nodes:+ rollup_state = ((rollup_nodes[0].get("commit") or {}).get("statusCheckRollup") or {}).get("state")+ statuses[reference] = self._map_ci_status(rollup_state)+ return statuses+_PR_BABYSIT_SNAPSHOT_QUERY = """query($owner: String!, $repo: String!, $number: Int!) {repository(owner: $owner, name: $repo) {diff --git a/posthog/models/test/integration/test_github.py b/posthog/models/test/integration/test_github.pyindex da5702164a85..6dd53d189671 100644--- a/posthog/models/test/integration/test_github.py+++ b/posthog/models/test/integration/test_github.py@@ -27,6 +27,7 @@ from posthog.models.github_integration_base import (GITHUB_BRANCH_CACHE_TTL_SECONDS,GITHUB_REPOSITORY_CACHE_TTL_SECONDS,GitHubIntegrationBase,+ PullRequestRef,)from posthog.models.integration import (GitHubInstallationAccessFetchError,@@ -2290,3 +2291,52 @@ class TestGitHubIntegrationPullRequestBabysitSnapshot(BaseTest):result = self._github().get_pull_request_babysit_snapshot(BABYSIT_PR_URL)assert result["success"] is False+++class TestGitHubIntegrationPullRequestCiStatuses(BaseTest):+ def _github(self) -> GitHubIntegration:+ return GitHubIntegration(_create_github_integration(self.team))++ @staticmethod+ def _rollup(state: str | None) -> dict:+ return {"pullRequest": {"commits": {"nodes": [{"commit": {"statusCheckRollup": {"state": state}}}]}}}++ def test_one_call_resolves_every_pull_request_against_its_own_reference(self):+ # The whole point of the batch: a list of PRs costs one GraphQL call, and each rollup lands on+ # the reference it was asked about. A mismatch here paints CI onto the wrong report.+ references = [+ PullRequestRef(owner="acme", repo="widgets", number=7),+ PullRequestRef(owner="acme", repo="widgets", number=8),+ PullRequestRef(owner="other", repo="thing", number=3),+ ]+ payload = {"pr0": self._rollup("SUCCESS"), "pr1": self._rollup("FAILURE"), "pr2": self._rollup(None)}++ with patch.object(GitHubIntegration, "_gh_graphql", return_value=payload) as mock_graphql:+ statuses = self._github().get_pull_request_ci_statuses(references)++ mock_graphql.assert_called_once()+ assert statuses == {references[0]: "passing", references[1]: "failing", references[2]: "none"}+ variables = mock_graphql.call_args.args[1]+ assert variables["owner2"] == "other" and variables["repo2"] == "thing" and variables["number2"] == 3++ def test_pull_requests_github_did_not_answer_for_are_left_out(self):+ # GitHub returns partial data when an alias hits a permission error, so an unreadable PR must+ # not take the readable ones down with it.+ readable = PullRequestRef(owner="acme", repo="widgets", number=7)+ unreadable = PullRequestRef(owner="private", repo="repo", number=1)++ with patch.object(GitHubIntegration, "_gh_graphql", return_value={"pr0": self._rollup("PENDING"), "pr1": None}):+ statuses = self._github().get_pull_request_ci_statuses([readable, unreadable])++ assert statuses == {readable: "pending"}++ def test_more_pull_requests_than_one_batch_holds_are_split_across_calls(self):+ # Without chunking a big inbox would build one query past GitHub's node limit and get nothing.+ batch_size = GitHubIntegration.PR_CI_STATUS_BATCH_SIZE+ references = [PullRequestRef(owner="acme", repo="widgets", number=n) for n in range(batch_size + 1)]++ with patch.object(GitHubIntegration, "_gh_graphql", return_value={}) as mock_graphql:+ self._github().get_pull_request_ci_statuses(references)++ assert mock_graphql.call_count == 2+ assert len(mock_graphql.call_args_list[1].args[1]) == 3 # owner/repo/number of the one leftoverdiff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.pyindex 1bca7b208220..e233fa716428 100644--- a/products/signals/backend/serializers.py+++ b/products/signals/backend/serializers.py@@ -3,7 +3,7 @@ from collections.abc import Mappingfrom datetime import datetimefrom typing import cast-from django.db.models import Q+from django.db.models import Q, TextChoicesfrom drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import PolymorphicProxySerializer, extend_schema_field@@ -1186,6 +1186,40 @@ class PullRequestChecksResponseSerializer(serializers.Serializer):checks = PullRequestCheckSerializer(many=True, read_only=True)+class PullRequestCiStatus(TextChoices):+ """Coarse rollup of a pull request's checks, as mapped from GitHub's status check rollup."""++ PASSING = "passing", "Passing"+ FAILING = "failing", "Failing"+ PENDING = "pending", "Pending"+ NONE = "none", "No checks"+++class PullRequestCiStatusSerializer(serializers.Serializer):+ """The CI rollup of one report's implementation pull request."""++ report_id = serializers.UUIDField(+ read_only=True, help_text="Report whose implementation pull request this status describes."+ )+ ci_status = serializers.ChoiceField(+ read_only=True,+ choices=PullRequestCiStatus.choices,+ help_text="Rollup of the pull request's checks on its head commit: 'passing' (nothing failed), "+ "'failing', 'pending' (checks are still running), or 'none' (the head commit has no checks).",+ )+++class PullRequestCiStatusesResponseSerializer(serializers.Serializer):+ """Response for the batch PR CI status endpoint, for painting CI state onto a list of reports."""++ statuses = PullRequestCiStatusSerializer(+ many=True,+ read_only=True,+ help_text="One entry per requested report whose CI state resolved. Reports without an open "+ "implementation pull request, and reports GitHub could not answer for, are left out.",+ )++class PullRequestCommentReactionSerializer(serializers.Serializer):"""One emoji reaction on a review comment, with the reactor so the viewer's own can be toggled."""diff --git a/products/signals/backend/test/test_signal_report_api.py b/products/signals/backend/test/test_signal_report_api.pyindex c9e4ba37c549..b5d129c47d24 100644--- a/products/signals/backend/test/test_signal_report_api.py+++ b/products/signals/backend/test/test_signal_report_api.py@@ -16,12 +16,13 @@ from django.test.utils import CaptureQueriesContextfrom django.utils import timezonefrom parameterized import parameterized-from rest_framework import status+from rest_framework import exceptions, statusfrom social_django.models import UserSocialAuth-from posthog.egress.github.transport import GitHubEgressBudgetExhausted+from posthog.egress.github.transport import GitHubEgressBudgetExhausted, GitHubRateLimitErrorfrom posthog.egress.limiter.policies import Priorityfrom posthog.models import OAuthApplication+from posthog.models.integration import GitHubIntegrationfrom posthog.models.team.team import Teamfrom posthog.models.user_integration import UserIntegrationfrom posthog.temporal.oauth import (@@ -33,6 +34,7 @@ from posthog.temporal.oauth import (from products.signals.backend.artefact_schemas import ChannelAssignmentfrom products.signals.backend.implementation_pr import (+ ImplementationPr,fetch_implementation_pr_state_for_reports,fetch_implementation_pr_urls_for_reports,)@@ -52,7 +54,11 @@ from products.signals.backend.task_run_artefacts import (record_implementation_task,record_report_task,)-from products.signals.backend.views import classify_report_list_client+from products.signals.backend.views import (+ PR_CI_STATUS_MAX_REPORTS,+ classify_report_list_client,+ parse_pr_ci_status_report_ids,+)from products.tasks.backend.facade.api import Channelfrom products.tasks.backend.facade.repo_selection_types import RepoSelectionResult@@ -2954,3 +2960,270 @@ class TestSignalReportPrEndpoints(APIBaseTest):assert response.status_code == status.HTTP_200_OKassert response.json() == {"comments": comments}+++class TestPrCiStatusReportIdsParsing(SimpleTestCase):+ @parameterized.expand(+ [+ ("missing", None),+ ("blank", " "),+ ("only_separators", ",,"),+ ("not_a_uuid", "not-a-uuid"),+ ("one_bad_id_among_good_ones", "3f1e0f4a-0000-4000-8000-000000000001,nope"),+ ]+ )+ def test_an_unusable_report_ids_param_is_rejected(self, _name, raw):+ # A list scan asks about ids it holds, so a malformed list is the caller's bug. Answering for+ # the ids that happen to parse would hide it behind rows that quietly never show CI state.+ with self.assertRaises(exceptions.ValidationError):+ parse_pr_ci_status_report_ids(raw)++ def test_more_ids_than_one_request_may_ask_about_are_rejected(self):+ raw = ",".join(str(uuid.uuid4()) for _ in range(PR_CI_STATUS_MAX_REPORTS + 1))+ with self.assertRaises(exceptions.ValidationError):+ parse_pr_ci_status_report_ids(raw)++ def test_padded_ids_are_accepted(self):+ report_id = uuid.uuid4()+ assert parse_pr_ci_status_report_ids(f" {report_id} , {report_id} ") == [report_id, report_id]+++class TestSignalReportPrCiStatuses(APIBaseTest):+ def setUp(self):+ super().setUp()+ # The resolved statuses are cached per team, repo, and PR, so a test must not read what an+ # earlier one warmed.+ cache.clear()+ self.addCleanup(cache.clear)++ def _create_report(self, title: str) -> SignalReport:+ return SignalReport.objects.create(+ team=self.team,+ status=SignalReport.Status.READY,+ title=title,+ summary="Test summary",+ signal_count=1,+ )++ def _url(self, report_ids) -> str:+ query = urlencode({"report_ids": ",".join(str(report_id) for report_id in report_ids)})+ return f"/api/projects/{self.team.id}/signals/reports/pr_ci_statuses/?{query}"++ @staticmethod+ def _pr(number: int, *, merged: bool = False) -> ImplementationPr:+ return ImplementationPr(url=f"https://github.com/PostHog/posthog/pull/{number}", merged=merged)++ def _patch_github(self):+ github = patch("products.signals.backend.views.GitHubIntegration.first_for_team_repository").start()+ self.addCleanup(patch.stopall)+ return github++ def test_open_prs_resolve_in_one_batch_and_everything_else_is_left_out(self):+ # The mapping is the whole contract: a report has to get its own PR's CI state, and a merged+ # or PR-less report must not be painted at all. One GitHub call covers the page.+ red = self._create_report("red")+ green = self._create_report("green")+ landed = self._create_report("landed")+ without_pr = self._create_report("no pr")+ github = self._patch_github()+ github.return_value.get_pull_request_ci_statuses.side_effect = lambda references: {+ reference: ("failing" if reference.number == 7 else "passing") for reference in references+ }++ with patch(+ "products.signals.backend.views.fetch_implementation_pr_state_for_reports",+ return_value={+ str(red.id): self._pr(7),+ str(green.id): self._pr(8),+ str(landed.id): self._pr(9, merged=True),+ },+ ):+ response = self.client.get(self._url([red.id, green.id, landed.id, without_pr.id]))++ assert response.status_code == status.HTTP_200_OK+ assert sorted(response.json()["statuses"], key=lambda entry: entry["report_id"]) == sorted(+ [+ {"report_id": str(red.id), "ci_status": "failing"},+ {"report_id": str(green.id), "ci_status": "passing"},+ ],+ key=lambda entry: entry["report_id"],+ )+ github.return_value.get_pull_request_ci_statuses.assert_called_once()+ requested = github.return_value.get_pull_request_ci_statuses.call_args.args[0]+ assert sorted(reference.number for reference in requested) == [7, 8]+ github.assert_called_once_with(+ self.team.id,+ "PostHog/posthog",+ source="signals_pr_ci_status",+ priority=Priority.NORMAL,+ )++ def test_a_second_scan_reads_the_cached_status_instead_of_calling_github(self):+ # Every list load and poll would otherwise cost a GitHub call per open PR.+ report = self._create_report("cached")+ github = self._patch_github()+ github.return_value.get_pull_request_ci_statuses.side_effect = lambda references: dict.fromkeys(+ references, "passing"+ )++ with patch(+ "products.signals.backend.views.fetch_implementation_pr_state_for_reports",+ return_value={str(report.id): self._pr(7)},+ ):+ first = self.client.get(self._url([report.id]))+ second = self.client.get(self._url([report.id]))++ assert first.json() == second.json() == {"statuses": [{"report_id": str(report.id), "ci_status": "passing"}]}+ github.return_value.get_pull_request_ci_statuses.assert_called_once()++ @parameterized.expand(+ [+ ("no_integration_reaches_the_repository", "lookup", None),+ ("the_lookup_is_rate_limited", "lookup", GitHubRateLimitError("slow down")),+ ("the_lookup_is_shed", "lookup", GitHubEgressBudgetExhausted("shed")),+ ("the_fetch_is_rate_limited", "fetch", GitHubRateLimitError("slow down")),+ ("the_fetch_is_shed", "fetch", GitHubEgressBudgetExhausted("shed")),+ ("the_fetch_fails_upstream", "fetch", Exception("boom")),+ ]+ )+ def test_the_list_still_loads_when(self, _name, failing_step, failure):+ # CI state decorates a list the reader already has. A GitHub problem has to cost them the+ # glyph, never the list.+ report = self._create_report("unreachable")+ github = self._patch_github()+ if failing_step == "lookup":+ github.return_value = None+ github.side_effect = failure+ else:+ github.return_value.get_pull_request_ci_statuses.side_effect = failure++ with patch(+ "products.signals.backend.views.fetch_implementation_pr_state_for_reports",+ return_value={str(report.id): self._pr(7)},+ ):+ response = self.client.get(self._url([report.id]))++ assert response.status_code == status.HTTP_200_OK+ assert response.json() == {"statuses": []}++ def test_a_batch_that_landed_before_a_rate_limit_is_kept(self):+ # An inbox wider than one GraphQL batch splits into several calls. Throwing away the batch+ # GitHub already answered for would cost every row its glyph, and the next poll would buy the+ # same answer again while GitHub is still limiting us.+ batch_size = GitHubIntegration.PR_CI_STATUS_BATCH_SIZE+ reports = [self._create_report(f"pr {n}") for n in range(batch_size + 1)]+ pr_by_report = {str(report.id): self._pr(n + 1) for n, report in enumerate(reports)}+ github = self._patch_github()+ calls: list[int] = []++ def fetch(references):+ calls.append(len(references))+ if len(calls) > 1:+ raise GitHubRateLimitError("slow down")+ return dict.fromkeys(references, "passing")++ github.return_value.get_pull_request_ci_statuses.side_effect = fetch+ url = self._url([report.id for report in reports])++ with patch(+ "products.signals.backend.views.fetch_implementation_pr_state_for_reports",+ return_value=pr_by_report,+ ):+ first = self.client.get(url)+ # The batch that never went out is not remembered as unreadable, because nothing was+ # learned about it, so it resolves as soon as GitHub answers again.+ github.return_value.get_pull_request_ci_statuses.side_effect = lambda references: dict.fromkeys(+ references, "passing"+ )+ second = self.client.get(url)++ assert calls == [batch_size, 1]+ assert len(first.json()["statuses"]) == batch_size+ assert len(second.json()["statuses"]) == batch_size + 1++ def test_another_teams_report_is_never_answered_for(self):+ other_team = Team.objects.create(organization=self.organization, name="other")+ other_report = SignalReport.objects.create(+ team=other_team, status=SignalReport.Status.READY, title="theirs", summary="s", signal_count=1+ )+ github = self._patch_github()++ with patch(+ "products.signals.backend.views.fetch_implementation_pr_state_for_reports",+ return_value={str(other_report.id): self._pr(7)},+ ) as fetch_pr_state:+ response = self.client.get(self._url([other_report.id]))++ assert response.status_code == status.HTTP_200_OK+ assert response.json() == {"statuses": []}+ fetch_pr_state.assert_not_called()+ github.assert_not_called()++ def test_a_malformed_report_ids_param_is_a_400(self):+ # Wiring guard for the parsing covered in TestPrCiStatusReportIdsParsing.+ response = self.client.get(f"/api/projects/{self.team.id}/signals/reports/pr_ci_statuses/?report_ids=nope")+ assert response.status_code == status.HTTP_400_BAD_REQUEST++ @parameterized.expand([("resolved", SignalReport.Status.RESOLVED), ("failed", SignalReport.Status.FAILED)])+ def test_a_terminal_report_costs_no_github_call(self, _name, report_status):+ # Its pull request has landed or been closed, so the pill never shows a CI glyph for it and+ # the fetch would be spent on something no reader can act on.+ report = self._create_report("terminal")+ SignalReport.objects.filter(id=report.id).update(status=report_status)+ github = self._patch_github()++ with patch(+ "products.signals.backend.views.fetch_implementation_pr_state_for_reports",+ return_value={str(report.id): self._pr(7)},+ ) as fetch_pr_state:+ response = self.client.get(self._url([report.id]))++ assert response.json() == {"statuses": []}+ fetch_pr_state.assert_not_called()+ github.assert_not_called()++ @parameterized.expand(+ [+ ("rate_limited", GitHubRateLimitError("slow down")),+ ("shed", GitHubEgressBudgetExhausted("shed")),+ ("failing_upstream", Exception("boom")),+ ]+ )+ def test_a_lookup_that_never_reached_github_is_asked_again(self, _name, failure):+ # A lookup that was throttled, shed, or failed learned nothing about the repository. Recording+ # it as unreadable would hold the glyph off the row for the whole five-minute window, over a+ # condition that usually clears within one poll.+ report = self._create_report("transient")+ github = self._patch_github()+ github.side_effect = failure++ with patch(+ "products.signals.backend.views.fetch_implementation_pr_state_for_reports",+ return_value={str(report.id): self._pr(7)},+ ):+ first = self.client.get(self._url([report.id]))+ github.side_effect = None+ github.return_value.get_pull_request_ci_statuses.side_effect = lambda references: dict.fromkeys(+ references, "passing"+ )+ second = self.client.get(self._url([report.id]))++ assert first.json() == {"statuses": []}+ assert second.json() == {"statuses": [{"report_id": str(report.id), "ci_status": "passing"}]}++ def test_a_pull_request_github_cannot_read_is_not_probed_again(self):+ # The repository probe and the query would otherwise run on every list load and every poll+ # for a pull request that is never going to resolve.+ report = self._create_report("unreadable")+ github = self._patch_github()+ github.return_value = None++ with patch(+ "products.signals.backend.views.fetch_implementation_pr_state_for_reports",+ return_value={str(report.id): self._pr(7)},+ ):+ first = self.client.get(self._url([report.id]))+ second = self.client.get(self._url([report.id]))++ assert first.json() == second.json() == {"statuses": []}+ github.assert_called_once()diff --git a/products/signals/backend/views.py b/products/signals/backend/views.pyindex a80335624f0e..3e48ef8f30d6 100644--- a/products/signals/backend/views.py+++ b/products/signals/backend/views.py@@ -1,7 +1,8 @@import reimport jsonimport uuid-from collections.abc import Callable, Sequence+from collections import defaultdict+from collections.abc import Callable, Iterable, Sequencefrom datetime import UTC, timedeltafrom functools import partialfrom typing import Any, cast@@ -59,7 +60,7 @@ from posthog.exceptions_capture import capture_exceptionfrom posthog.models import Team, Userfrom posthog.models.activity_logging.activity_log import Change, Detail, log_activityfrom posthog.models.activity_logging.model_activity import is_impersonated_session-from posthog.models.github_integration_base import GitHubIntegrationBase+from posthog.models.github_integration_base import GitHubIntegrationBase, PullRequestReffrom posthog.models.integration import GitHubIntegration, Integrationfrom posthog.models.team.extensions import get_or_create_team_extensionfrom posthog.models.user_integration import ReauthorizationRequired, UserGitHubIntegration, UserIntegration@@ -130,6 +131,7 @@ from products.signals.backend.reviewer_correction_notes import ReviewerCorrectiofrom products.signals.backend.serializers import (CommitDiffResponseSerializer,PullRequestChecksResponseSerializer,+ PullRequestCiStatusesResponseSerializer,PullRequestCommentsResponseSerializer,PullRequestReviewCommentCreateResponseSerializer,PullRequestReviewCommentCreateSerializer,@@ -189,6 +191,41 @@ tracer = trace.get_tracer(__name__)# old behaviour, which capped at 100 and dropped everyone alphabetically after ~"M").REVIEWER_PAGINATION_THRESHOLD = 1200PR_GITHUB_CACHE_SECONDS = 15+# The pill in a report list needs a glyph, not a live build log, so its CI state is cached longer+# than the detail view's checks. The detail view stays the authoritative, 15s-fresh read of the+# same pull request.+PR_CI_STATUS_CACHE_SECONDS = 60+# How long a pull request GitHub cannot answer for is remembered as unreadable.+PR_CI_STATUS_UNREADABLE_CACHE_SECONDS = 300+# Reports one batch CI-status request may ask about. A report list page is 50 rows, so a full page+# of pull requests fits, with room for a flat list that merges several sections.+PR_CI_STATUS_MAX_REPORTS = 100+# Cached in place of a CI status for a pull request GitHub cannot answer for. Not a member of the+# status vocabulary, so it can never be served to a caller as one.+_PR_CI_STATUS_UNREADABLE = "unreadable"+# Report statuses whose pull request is no longer open, so its CI is not worth a GitHub call.+_PR_CI_STATUS_TERMINAL_REPORT_STATUSES = frozenset(+ {SignalReport.Status.FAILED, SignalReport.Status.SUPPRESSED, SignalReport.Status.RESOLVED}+)+++def parse_pr_ci_status_report_ids(raw: str | None) -> list[uuid.UUID]:+ """Parse the batch CI-status endpoint's comma-separated `report_ids`.++ A malformed or oversized list is the caller's bug, not a report that has no CI state, so it+ fails loudly instead of answering for the ids that happened to parse.+ """+ ids = [part.strip() for part in (raw or "").split(",") if part.strip()]+ if not ids:+ raise exceptions.ValidationError({"report_ids": "Pass at least one report id."})+ if len(ids) > PR_CI_STATUS_MAX_REPORTS:+ raise exceptions.ValidationError(+ {"report_ids": f"Pass at most {PR_CI_STATUS_MAX_REPORTS} report ids per request."}+ )+ try:+ return [uuid.UUID(report_id) for report_id in ids]+ except ValueError:+ raise exceptions.ValidationError({"report_ids": "Every report id must be a UUID."})def classify_report_list_client(user_agent: str | None) -> str:@@ -854,10 +891,11 @@ class SignalReportViewSet(}def safely_get_queryset(self, queryset):- if self.action == "viewed":- # Passive telemetry fired right after the detail request that already rendered the- # report: only visibility matters here, so skip the rendering annotations and- # prefetches every other action's serializer needs.+ if self.action in {"viewed", "pr_ci_statuses"}:+ # Neither action renders a report, so both skip the rendering annotations and prefetches+ # every other action's serializer needs. `viewed` is passive telemetry fired right after+ # the detail request that already rendered the report, and `pr_ci_statuses` only needs to+ # know which of the requested ids are this team's.qs = queryset.filter(team=self.team)return self._apply_signal_report_status_filter(qs)if self.action in {"retrieve", "signals"}:@@ -2991,6 +3029,168 @@ class SignalReportViewSet(cast(SignalReport, self.get_object()), "get_pull_request_checks", "checks", "checks")+ @extend_schema(+ parameters=[+ OpenApiParameter(+ "report_ids",+ OpenApiTypes.STR,+ description=(+ "Comma-separated report UUIDs to resolve CI state for, at most "+ f"{PR_CI_STATUS_MAX_REPORTS} per request."+ ),+ required=True,+ )+ ],+ responses={+ 200: OpenApiResponse(+ response=PullRequestCiStatusesResponseSerializer,+ description="The CI rollup of each requested report's implementation pull request.",+ ),+ 400: OpenApiResponse(description="`report_ids` is missing, not a list of UUIDs, or over the cap."),+ },+ summary="Fetch CI status for several reports' implementation PRs",+ description=(+ "Resolve the coarse CI rollup of the pull requests several reports opened, so a list of "+ "reports can show which pull requests are red without opening each report. One GitHub "+ "call covers the whole batch, and the answers are cached briefly and shared across "+ "callers. A report is left out when it has no open implementation pull request, and also "+ "when GitHub could not answer for it (no integration reaches the repository, a rate "+ "limit, an upstream failure), so a caller shows no CI state for it rather than an error. "+ "For the individual checks behind the rollup, use `pr_checks`."+ ),+ operation_id="signals_reports_pr_ci_statuses",+ )+ @action(detail=False, methods=["get"], url_path="pr_ci_statuses", required_scopes=["task:read"])+ def pr_ci_statuses(self, request: Request, **kwargs) -> Response:+ requested_ids = parse_pr_ci_status_report_ids(request.query_params.get("report_ids"))+ # Team-scoped via `get_queryset`, so an id belonging to another team resolves to nothing.+ # A report in a terminal status is dropped here rather than fetched: its pull request has been+ # closed or landed, so the pill reads "merged" or "closed" and the reader has nothing to act+ # on. This mirrors the frontend's `derivePrState`, which paints a glyph on an open pill only.+ report_ids = [+ str(report_id)+ for report_id, report_status in self.get_queryset().filter(id__in=requested_ids).values_list("id", "status")+ if report_status not in _PR_CI_STATUS_TERMINAL_REPORT_STATUSES+ ]+ if not report_ids:+ return self._pr_ci_statuses_response([])++ try:+ pr_by_report = fetch_implementation_pr_state_for_reports(report_ids)+ except Exception:+ # Decorative metadata: a lookup failure must leave the list unpainted, not broken.+ logger.exception("signals.reports.pr_ci_statuses.implementation_pr_lookup_failed")+ return self._pr_ci_statuses_response([])++ # Merged pull requests are skipped for the same reason: the pill already reads "merged", and+ # the CI of a landed pull request is history rather than something a reader can act on.+ references: dict[str, PullRequestRef] = {}+ for report_id, pr in pr_by_report.items():+ if pr.merged:+ continue+ parsed = GitHubIntegration.parse_pull_request_url(pr.url)+ if parsed is not None:+ references[report_id] = parsed++ statuses = self._pr_ci_statuses_for_references(references.values())+ return self._pr_ci_statuses_response(+ [+ {"report_id": report_id, "ci_status": statuses[reference]}+ for report_id, reference in references.items()+ if reference in statuses+ ]+ )++ @staticmethod+ # `list` names the viewset's own action inside the class body, so the annotation uses `Sequence`.+ def _pr_ci_statuses_response(statuses: Sequence[dict[str, str]]) -> Response:+ """Render the batch CI-status payload through its declared response serializer, so the wire+ shape cannot drift from the OpenAPI schema the frontend types and MCP tools are built from."""+ return Response(PullRequestCiStatusesResponseSerializer({"statuses": statuses}).data)++ def _pr_ci_statuses_for_references(self, references: Iterable[PullRequestRef]) -> dict[PullRequestRef, str]:+ """CI rollup per pull request, from the shared cache where it is warm and one batched GitHub+ call per integration for the rest. A pull request GitHub cannot answer for is absent from the+ result: this paints a glyph onto a list, so it degrades to no glyph rather than to an error."""+ resolved: dict[PullRequestRef, str] = {}+ misses_by_repository: dict[str, list[PullRequestRef]] = defaultdict(list)+ for reference in dict.fromkeys(references):+ cached = cache.get(self._pr_ci_status_cache_key(reference))+ if cached == _PR_CI_STATUS_UNREADABLE:+ continue+ if isinstance(cached, str):+ resolved[reference] = cached+ else:+ misses_by_repository[reference.repository].append(reference)++ # An installation is granted per repository, so one integration lookup per repository is what+ # bounds the access probes. Repositories that share an installation collapse into one query.+ batches: dict[int, tuple[GitHubIntegration, list[PullRequestRef]]] = {}+ for repository, repository_references in misses_by_repository.items():+ try:+ github = GitHubIntegration.first_for_team_repository(+ self.team.id, repository, source="signals_pr_ci_status", priority=Priority.NORMAL+ )+ except (GitHubRateLimitError, GitHubEgressBudgetExhausted):+ # The probe never reached GitHub, so nothing was learned about the repository. Same+ # policy as a throttled fetch below: remember nothing and let the next poll ask again.+ logger.info("signals.reports.pr_ci_statuses.lookup_throttled", repository=repository)+ continue+ except Exception:+ logger.warning(+ "signals.reports.pr_ci_statuses.integration_lookup_failed", repository=repository, exc_info=True+ )+ continue+ if github is None:+ # GitHub answered, and no installation reaches the repository. That is stable enough+ # to remember, so the probe does not run again on every load and every poll.+ self._remember_unreadable_pr_ci_statuses(repository_references)+ continue+ _, pending = batches.setdefault(github.integration.id, (github, []))+ pending.extend(repository_references)++ for github, pending in batches.values():+ # One call per batch, cached as it lands, so a failure costs the batches it stopped and+ # not the ones GitHub already answered for. Stop this integration at the first failure:+ # another call would spend the same budget on the same condition.+ batch_size = GitHubIntegration.PR_CI_STATUS_BATCH_SIZE+ for start in range(0, len(pending), batch_size):+ batch = pending[start : start + batch_size]+ try:+ fetched = github.get_pull_request_ci_statuses(batch)+ except (GitHubRateLimitError, GitHubEgressBudgetExhausted):+ # Expected under load, and the reader loses nothing they had: skip the glyph and+ # let the next request (or the detail view) answer once the limit clears.+ logger.info("signals.reports.pr_ci_statuses.throttled", pr_count=len(batch))+ break+ except Exception:+ logger.warning("signals.reports.pr_ci_statuses.fetch_failed", pr_count=len(batch), exc_info=True)+ break+ for reference, ci_status in fetched.items():+ cache.set(self._pr_ci_status_cache_key(reference), ci_status, timeout=PR_CI_STATUS_CACHE_SECONDS)+ resolved[reference] = ci_status+ # GitHub answered the batch but left this pull request out, so the installation cannot+ # read it (deleted, transferred, or access revoked). That is stable enough to remember.+ self._remember_unreadable_pr_ci_statuses([ref for ref in batch if ref not in fetched])+ return resolved++ def _remember_unreadable_pr_ci_statuses(self, references: Iterable[PullRequestRef]) -> None:+ """Remember, briefly, that GitHub cannot answer for these pull requests.++ Without this every list load and every poll re-runs the per-repository access probe, and then+ the query, for a pull request that is never going to resolve. The window is short so access+ granted a moment later still takes effect quickly.+ """+ for reference in references:+ cache.set(+ self._pr_ci_status_cache_key(reference),+ _PR_CI_STATUS_UNREADABLE,+ timeout=PR_CI_STATUS_UNREADABLE_CACHE_SECONDS,+ )++ def _pr_ci_status_cache_key(self, reference: PullRequestRef) -> str:+ return f"signals:pr-ci-status:{self.team.id}:{reference.repository}:{reference.number}"+@extend_schema(responses={200: OpenApiResponse(diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex 75053a8d4a77..681ddcf7e881 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -1894,6 +1894,44 @@ export interface SignalReportBulkStateResponseApi {not_found_count: number}+/**+ * * `passing` - Passing+ * * `failing` - Failing+ * * `pending` - Pending+ * * `none` - No checks+ */+export type PullRequestCiStatusEnumApi = (typeof PullRequestCiStatusEnumApi)[keyof typeof PullRequestCiStatusEnumApi]++export const PullRequestCiStatusEnumApi = {+ Passing: 'passing',+ Failing: 'failing',+ Pending: 'pending',+ None: 'none',+} as const++/**+ * The CI rollup of one report's implementation pull request.+ */+export interface PullRequestCiStatusApi {+ /** Report whose implementation pull request this status describes. */+ readonly report_id: string+ /** Rollup of the pull request's checks on its head commit: 'passing' (nothing failed), 'failing', 'pending' (checks are still running), or 'none' (the head commit has no checks).+ *+ * * `passing` - Passing+ * * `failing` - Failing+ * * `pending` - Pending+ * * `none` - No checks */+ readonly ci_status: PullRequestCiStatusEnumApi+}++/**+ * Response for the batch PR CI status endpoint, for painting CI state onto a list of reports.+ */+export interface PullRequestCiStatusesResponseApi {+ /** One entry per requested report whose CI state resolved. Reports without an open implementation pull request, and reports GitHub could not answer for, are left out. */+ readonly statuses: readonly PullRequestCiStatusApi[]+}+export interface SignalReportRefundSummaryResponseApi {/** Number of credited-path refunds across the whole organization whose refunded PR run falls in the current billing period. Excluded-path refunds never reach billing usage, so they are deliberately absent. */credited_refund_count: number@@ -4450,6 +4488,13 @@ export type SignalsReportArtefactsListParams = {offset?: number}+export type SignalsReportsPrCiStatusesParams = {+ /**+ * Comma-separated report UUIDs to resolve CI state for, at most 100 per request.+ */+ report_ids: string+}+export type SignalsScoutConfigListParams = {/*** Comma-separated tags, e.g. `revenue,on-call`. Returns the scouts carrying at least one of them. Values are normalized the same way stored tags are, so `On Call` matches `on-call`. Omit for the whole fleet.diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.tsindex a20a95c8dc74..dc54a1a7882c 100644--- a/products/signals/frontend/generated/api.ts+++ b/products/signals/frontend/generated/api.ts@@ -32,6 +32,7 @@ import type {PauseUntilRequestApi,ProjectProfileApi,PullRequestChecksResponseApi,+ PullRequestCiStatusesResponseApi,PullRequestCommentsResponseApi,PullRequestReviewCommentCreateApi,PullRequestReviewCommentCreateResponseApi,@@ -80,6 +81,7 @@ import type {SignalsProcessingListParams,SignalsReportArtefactsListParams,SignalsReportsListParams,+ SignalsReportsPrCiStatusesParams,SignalsScoutConfigListParams,SignalsScoutConfigSyncParams,SignalsScoutMembersListParams,@@ -713,6 +715,37 @@ export const signalsReportsBulkStateCreate = async (})}+export const getSignalsReportsPrCiStatusesUrl = (projectId: string, params: SignalsReportsPrCiStatusesParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/signals/reports/pr_ci_statuses/?${stringifiedParams}`+ : `/api/projects/${projectId}/signals/reports/pr_ci_statuses/`+}++/**+ * Resolve the coarse CI rollup of the pull requests several reports opened, so a list of reports can show which pull requests are red without opening each report. One GitHub call covers the whole batch, and the answers are cached briefly and shared across callers. A report is left out when it has no open implementation pull request, and also when GitHub could not answer for it (no integration reaches the repository, a rate limit, an upstream failure), so a caller shows no CI state for it rather than an error. For the individual checks behind the rollup, use `pr_checks`.+ * @summary Fetch CI status for several reports' implementation PRs+ */+export const signalsReportsPrCiStatuses = async (+ projectId: string,+ params: SignalsReportsPrCiStatusesParams,+ options?: RequestInit+): Promise<PullRequestCiStatusesResponseApi> => {+ return apiMutator<PullRequestCiStatusesResponseApi>(getSignalsReportsPrCiStatusesUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}+export const getSignalsReportsRefundSummaryRetrieveUrl = (projectId: string) => {return `/api/projects/${projectId}/signals/reports/refund-summary/`}diff --git a/products/signals/frontend/inbox/components/cards/ReportCard.tsx b/products/signals/frontend/inbox/components/cards/ReportCard.tsxindex 778b649aaf3c..7a5ede2bcf91 100644--- a/products/signals/frontend/inbox/components/cards/ReportCard.tsx+++ b/products/signals/frontend/inbox/components/cards/ReportCard.tsx@@ -1,4 +1,5 @@import clsx from 'clsx'+import { useValues } from 'kea'import { router } from 'kea-router'import { IconHide, IconUndo } from '@posthog/icons'@@ -6,11 +7,12 @@ import { LemonButton, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'import { TZLabel } from 'lib/components/TZLabel'import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'-import { derivePrState } from 'lib/signals/prState'+import { derivePrState, prCiGlyphStatus } from 'lib/signals/prState'import { ScoutLink } from 'lib/signals/ScoutLink'import { scoutDisplayName } from 'lib/signals/signalCardSourceLine'import { PrBadge } from 'lib/signals/SignalReportPrBadge'+import { prCiStatusLogic } from '../../logics/prCiStatusLogic'import {INBOX_SECTION_LEGACY_TAB,InboxReportSectionKey,@@ -161,6 +163,12 @@ export function ReportCard({onDismiss,})+ // Painted from the shared map the report lists fill; absent until (or unless) GitHub answers.+ const { ciStatusByReportId } = useValues(prCiStatusLogic)+ const ciStatus = preview ? null : ciStatusByReportId[report.id]+ const prState = derivePrState(report.status, report.implementation_pr_merged === true)+ const glyphStatus = prCiGlyphStatus(prState, ciStatus)+const isRefunded = !!report.refundconst showsDismiss = !!onDismiss || !redesign@@ -188,7 +196,9 @@ export function ReportCard({<divclassName={clsx('min-w-0 break-words font-semibold text-sm leading-snug text-balance',- hasPr && 'pr-14'+ // A CI glyph widens the pill, so the title gives back the space it takes.+ // A state that draws no glyph keeps the pill at its plain width.+ hasPr && (glyphStatus ? 'pr-24' : 'pr-14'))}>{conventionalTitle && (@@ -275,7 +285,8 @@ export function ReportCard({// No link in preview mode: the sample PR url is fabricated, and a link would// stay keyboard-focusable inside the otherwise non-routable card.prUrl={preview ? null : prUrl}- state={derivePrState(report.status, report.implementation_pr_merged === true)}+ state={prState}+ ciStatus={ciStatus}/></div>) : null}diff --git a/products/signals/frontend/inbox/logics/prCiStatusLogic.test.ts b/products/signals/frontend/inbox/logics/prCiStatusLogic.test.tsnew file mode 100644index 000000000000..b8ddf08a5111--- /dev/null+++ b/products/signals/frontend/inbox/logics/prCiStatusLogic.test.ts@@ -0,0 +1,153 @@+/* oxlint-disable react-hooks/rules-of-hooks -- useMocks is a test helper, not a React hook */+import { expectLogic } from 'kea-test-utils'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { PR_CI_STATUS_MAX_AGE_MS, PR_CI_STATUS_MAX_REPORTS, prCiStatusLogic } from './prCiStatusLogic'++const CI_STATUSES_URL = '/api/projects/:team_id/signals/reports/pr_ci_statuses/'++describe('prCiStatusLogic', () => {+ let logic: ReturnType<typeof prCiStatusLogic.build>+ let requestedIds: string[][]+ let answers: Record<string, string>++ beforeEach(() => {+ requestedIds = []+ answers = { 'report-1': 'failing', 'report-2': 'passing' }+ useMocks({+ get: {+ [CI_STATUSES_URL]: ({ request }) => {+ const ids = (new URL(request.url).searchParams.get('report_ids') ?? '').split(',')+ requestedIds.push(ids)+ return [+ 200,+ {+ statuses: ids+ .filter((id) => id in answers)+ .map((id) => ({ report_id: id, ci_status: answers[id] })),+ },+ ]+ },+ },+ })+ initKeaTests()+ logic = prCiStatusLogic()+ logic.mount()+ })++ afterEach(() => logic.unmount())++ it('resolves every report the sections announce in one request', async () => {+ logic.actions.trackReports('needs-decision', ['report-1'])+ logic.actions.trackReports('monitoring', ['report-2'])+ await expectLogic(logic).toFinishAllListeners()++ // Two sections announcing separately still cost one round trip, which is what makes a glyph+ // on every row affordable.+ expect(requestedIds).toEqual([['report-1', 'report-2']])+ expect(logic.values.ciStatusByReportId).toEqual({ 'report-1': 'failing', 'report-2': 'passing' })+ })++ it('covers every tracked report when there are more than one request may carry', async () => {+ // A reader who loads a third page, or merges several sections into the flat list, tracks more+ // rows than the endpoint answers for in one request. Cutting the list short there would leave+ // those rows without a glyph for as long as they stayed on screen.+ const reportIds = Array.from({ length: PR_CI_STATUS_MAX_REPORTS + 5 }, (_, index) => `report-${index}`)+ answers = Object.fromEntries(reportIds.map((reportId) => [reportId, 'passing']))++ logic.actions.trackReports('needs-decision', reportIds)+ await expectLogic(logic).toFinishAllListeners()++ expect(requestedIds).toHaveLength(2)+ expect(requestedIds.every((ids) => ids.length <= PR_CI_STATUS_MAX_REPORTS)).toBe(true)+ expect(requestedIds.flat().sort()).toEqual([...reportIds].sort())+ expect(Object.keys(logic.values.ciStatusByReportId)).toHaveLength(reportIds.length)+ })++ it('holds the last known state for a report the next answer leaves out', async () => {+ logic.actions.trackReports('needs-decision', ['report-1'])+ await expectLogic(logic).toFinishAllListeners()++ // GitHub rate-limiting a poll drops the report from the answer. Clearing its glyph would+ // read as "this pull request has no checks", which is a different and wrong claim.+ answers = {}+ logic.actions.loadCiStatuses({ reportIds: ['report-1'] })+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.ciStatusByReportId).toEqual({ 'report-1': 'failing' })+ })++ it('stops showing a state nothing has confirmed for two polls', async () => {+ logic.actions.trackReports('needs-decision', ['report-1'])+ await expectLogic(logic).toFinishAllListeners()++ // A rate limit that lasts, or access GitHub has revoked, leaves the report out of every+ // answer. Holding the glyph indefinitely would let the pill claim a pull request is failing+ // or passing long after its CI moved on.+ const confirmedAt = Date.now()+ answers = {}+ const nowSpy = jest.spyOn(Date, 'now').mockReturnValue(confirmedAt + PR_CI_STATUS_MAX_AGE_MS + 1)+ try {+ logic.actions.loadCiStatuses({ reportIds: ['report-1'] })+ await expectLogic(logic).toFinishAllListeners()+ } finally {+ nowSpy.mockRestore()+ }++ expect(logic.values.ciStatusByReportId).toEqual({})+ })++ it('forgets a report that has left the tracked set', async () => {+ logic.actions.trackReports('needs-decision', ['report-1'])+ await expectLogic(logic).toFinishAllListeners()++ // Otherwise the map grows for as long as the inbox stays open.+ logic.actions.loadCiStatuses({ reportIds: ['report-2'] })+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.ciStatusByReportId).toEqual({ 'report-2': 'passing' })+ })++ it('does not re-ask for reports it has already requested', async () => {+ // Every list re-render announces the same rows; re-fetching each time would hammer GitHub.+ logic.actions.trackReports('needs-decision', ['report-1'])+ await expectLogic(logic).toFinishAllListeners()+ logic.actions.trackReports('needs-decision', ['report-1'])+ await expectLogic(logic).toFinishAllListeners()++ expect(requestedIds).toHaveLength(1)+ })++ it('asks again for a row the section dropped and then showed again', async () => {+ logic.actions.trackReports('needs-decision', ['report-1'])+ await expectLogic(logic).toFinishAllListeners()++ // Filtering the inbox to resolved reports leaves a section with nothing to announce, and the+ // poll pauses while nothing is tracked. Repainting the old glyph when the filter clears would+ // claim a CI state of unknown age.+ logic.actions.trackReports('needs-decision', [])+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.ciStatusByReportId).toEqual({})++ answers = { 'report-1': 'passing' }+ logic.actions.trackReports('needs-decision', ['report-1'])+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.ciStatusByReportId).toEqual({ 'report-1': 'passing' })+ // An empty announcement is answered without a request, so only the two real loads count.+ expect(requestedIds).toHaveLength(2)+ })++ it('retires the rows a section stops showing', async () => {+ // A narrowed filter drops rows from a section. Keeping them would leave the poll asking+ // GitHub about pull requests nobody is looking at, for as long as the inbox stays open.+ logic.actions.trackReports('needs-decision', ['report-1', 'report-2'])+ await expectLogic(logic).toFinishAllListeners()+ logic.actions.trackReports('needs-decision', ['report-2'])+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.trackedReportIds).toEqual(['report-2'])+ })+})diff --git a/products/signals/frontend/inbox/logics/prCiStatusLogic.ts b/products/signals/frontend/inbox/logics/prCiStatusLogic.tsnew file mode 100644index 000000000000..4187d12fa12b--- /dev/null+++ b/products/signals/frontend/inbox/logics/prCiStatusLogic.ts@@ -0,0 +1,225 @@+import { MakeLogicType, actions, afterMount, kea, listeners, path, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'++import { teamLogic } from 'scenes/teamLogic'++import { signalsReportsPrCiStatuses } from 'products/signals/frontend/generated/api'+import type { PullRequestCiStatusEnumApi } from 'products/signals/frontend/generated/api.schemas'++/** CI state per report id. A report GitHub has not answered for is simply absent. */+export type PrCiStatusMap = Record<string, PullRequestCiStatusEnumApi>++/** How often the tracked pull requests are re-read while the inbox is open. */+export const PR_CI_STATUS_POLL_INTERVAL_MS = 60_000+/**+ * How long a state GitHub has stopped answering for is still shown. Two polls of slack ride out a+ * rate limit, and past that the glyph goes: a pill that keeps claiming a CI state nothing confirms+ * is worse than a pill with no glyph.+ */+export const PR_CI_STATUS_MAX_AGE_MS = 2 * PR_CI_STATUS_POLL_INTERVAL_MS+/** Reports one request may ask about, above which the endpoint rejects the list. */+export const PR_CI_STATUS_MAX_REPORTS = 100+/** Sections load independently, so their bursts coalesce into one load. */+const PR_CI_STATUS_DEBOUNCE_MS = 50++/** A resolved CI state and when GitHub last confirmed it, so a held state can age out. */+interface ConfirmedCiStatus {+ ciStatus: PullRequestCiStatusEnumApi+ confirmedAt: number+}++/** The announced rows, in requests no longer than the endpoint will answer for. */+function chunkReportIds(reportIds: string[]): string[][] {+ const chunks: string[][] = []+ for (let start = 0; start < reportIds.length; start += PR_CI_STATUS_MAX_REPORTS) {+ chunks.push(reportIds.slice(start, start + PR_CI_STATUS_MAX_REPORTS))+ }+ return chunks+}++/**+ * Whether two announcements cover the same rows. Both lists are deduplicated, so length and+ * membership are enough, and neither list's order carries meaning.+ */+function coversSameReports(reportIds: string[], other: string[]): boolean {+ return reportIds.length === other.length && reportIds.every((reportId) => other.includes(reportId))+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface prCiStatusLogicValues {+ ciStatusByReportId: PrCiStatusMap+ ciStatusByReportIdLoading: boolean+ requestedReportIds: string[]+ trackedReportIds: string[]+ trackedReportIdsBySource: Record<string, string[]>+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface prCiStatusLogicActions {+ loadCiStatuses: ({ reportIds }: { reportIds: string[] }) => {+ reportIds: string[]+ }+ loadCiStatusesFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadCiStatusesSuccess: (+ ciStatusByReportId: {+ [k: string]: PullRequestCiStatusEnumApi+ },+ payload?: {+ reportIds: string[]+ }+ ) => {+ ciStatusByReportId: {+ [k: string]: PullRequestCiStatusEnumApi+ }+ payload?: {+ reportIds: string[]+ }+ }+ trackReports: (+ source: string,+ reportIds: string[]+ ) => {+ reportIds: string[]+ source: string+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface prCiStatusLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ trackedReportIds: (trackedReportIdsBySource: Record<string, string[]>) => string[]+ }+}++export type prCiStatusLogicType = MakeLogicType<+ prCiStatusLogicValues,+ prCiStatusLogicActions,+ Record<string, any>,+ prCiStatusLogicMeta+>++/**+ * CI state of the implementation pull requests the report lists show, so a reader scanning the inbox+ * can see which pull requests are red without opening each report in turn.+ *+ * Shared rather than keyed: every report section paints the same pill, and the flat list merges+ * several sections, so one map serves them all and a report listed twice costs one lookup. Sections+ * announce the reports they show through `trackReports`; the backend resolves each request's set in+ * one batched GitHub read, and a poll keeps a running build's glyph moving while the inbox stays+ * open.+ */+export const prCiStatusLogic = kea<prCiStatusLogicType>([+ path(['scenes', 'inbox', 'logics', 'prCiStatusLogic']),++ actions({+ trackReports: (source: string, reportIds: string[]) => ({ source, reportIds }),+ }),++ loaders(({ cache }) => ({+ ciStatusByReportId: [+ {} as PrCiStatusMap,+ {+ loadCiStatuses: async ({ reportIds }: { reportIds: string[] }, breakpoint) => {+ const teamId = teamLogic.values.currentTeamId+ if (!teamId || reportIds.length === 0) {+ cache.confirmedCiStatuses = {}+ return {}+ }+ // The endpoint rejects a list longer than it will answer for, so a longer set is+ // asked for in several requests instead of being cut short: a row on the third+ // page a reader loaded needs its glyph as much as a row on the first.+ const responses = await Promise.all(+ chunkReportIds(reportIds).map((chunk) =>+ signalsReportsPrCiStatuses(String(teamId), { report_ids: chunk.join(',') })+ )+ )+ breakpoint()+ const now = Date.now()+ const confirmed: Record<string, ConfirmedCiStatus> = { ...cache.confirmedCiStatuses }+ for (const entry of responses.flatMap((response) => response.statuses)) {+ confirmed[entry.report_id] = { ciStatus: entry.ci_status, confirmedAt: now }+ }+ // Merge forward, then keep only the reports still on screen whose state is young+ // enough: a pull request GitHub could not answer for this time holds the state it+ // last had instead of losing its glyph for a poll, and a report that scrolled out+ // is forgotten. A rate limit or revoked access leaves the same report out of every+ // answer, so the state also expires, rather than claim a CI state for as long as+ // the reader keeps the inbox open.+ const kept = reportIds.filter(+ (reportId) =>+ reportId in confirmed && now - confirmed[reportId].confirmedAt <= PR_CI_STATUS_MAX_AGE_MS+ )+ cache.confirmedCiStatuses = Object.fromEntries(+ kept.map((reportId) => [reportId, confirmed[reportId]])+ )+ return Object.fromEntries(kept.map((reportId) => [reportId, confirmed[reportId].ciStatus]))+ },+ },+ ],+ })),++ reducers({+ // Kept per announcing section, so a section that narrows its filter stops asking about rows it+ // no longer shows. Accumulating one flat set instead would keep every row a reader ever+ // scrolled past in the poll for as long as the inbox stayed open.+ trackedReportIdsBySource: [+ {} as Record<string, string[]>,+ {+ trackReports: (+ state: Record<string, string[]>,+ { source, reportIds }: { source: string; reportIds: string[] }+ ) => ({ ...state, [source]: reportIds }),+ },+ ],+ // What the last request covered, so a section re-rendering the same rows doesn't re-ask.+ requestedReportIds: [+ [] as string[],+ {+ loadCiStatuses: (_: string[], { reportIds }: { reportIds: string[] }) => reportIds,+ },+ ],+ }),++ selectors({+ // Every row the sections announce, deduplicated. Not capped to what one request carries: the+ // loader splits a longer set, so a reader who pages past the first hundred rows still gets+ // a glyph on the rest.+ trackedReportIds: [+ (s) => [s.trackedReportIdsBySource],+ (trackedReportIdsBySource: Record<string, string[]>): string[] =>+ Array.from(new Set(Object.values(trackedReportIdsBySource).flat())),+ ],+ }),++ listeners(({ actions, values }) => ({+ trackReports: async (_, breakpoint) => {+ // A section re-rendering the same rows must not re-ask. Any other set has to: a new row+ // has no state yet, and a row that left and came back may have gone stale while the poll+ // was not covering it. An empty set costs no request and clears the rows that left.+ if (coversSameReports(values.trackedReportIds, values.requestedReportIds)) {+ return+ }+ await breakpoint(PR_CI_STATUS_DEBOUNCE_MS)+ actions.loadCiStatuses({ reportIds: values.trackedReportIds })+ },+ })),++ afterMount(({ actions, values, cache }) => {+ // A build that goes red while someone is reading the list should show it. Auto-disposed on+ // unmount and paused on a hidden tab, so a backgrounded inbox costs GitHub nothing.+ cache.disposables.add(() => {+ const interval = setInterval(() => {+ if (values.trackedReportIds.length > 0) {+ actions.loadCiStatuses({ reportIds: values.trackedReportIds })+ }+ }, PR_CI_STATUS_POLL_INTERVAL_MS)+ return () => clearInterval(interval)+ }, 'prCiStatusPoll')+ }),+])diff --git a/products/signals/frontend/inbox/logics/reportListLogic.test.ts b/products/signals/frontend/inbox/logics/reportListLogic.test.tsindex a1179650b5cd..a501b56ee321 100644--- a/products/signals/frontend/inbox/logics/reportListLogic.test.ts+++ b/products/signals/frontend/inbox/logics/reportListLogic.test.ts@@ -182,4 +182,53 @@ describe('reportListLogic', () => {expect(logic.values.reports).toHaveLength(FIRST_PAGE.length + SECOND_PAGE.length)})})++ // Which rows get a CI glyph, and which pull requests the batch endpoint is asked about. A landed+ // or dropped pull request has no CI worth reading, and asking about it spends a GitHub call.+ describe('open pull requests on the page', () => {+ let logic: ReturnType<typeof reportListLogic.build>++ const withPr = (id: string, overrides: Partial<SignalReport>): SignalReport => ({+ ...makeReport(id),+ implementation_pr_url: `https://github.com/PostHog/posthog/pull/${id}`,+ ...overrides,+ })++ beforeEach(async () => {+ useMocks({+ get: {+ '/api/projects/:team_id/signals/reports/available_reviewers': {},+ '/api/projects/:team_id/signals/reports/pr_ci_statuses/': { statuses: [] },+ [REPORTS_URL]: () => [+ 200,+ {+ count: 4,+ next: null,+ previous: null,+ results: [+ withPr('1', {}),+ withPr('2', { implementation_pr_merged: true }),+ withPr('3', { status: SignalReportStatus.SUPPRESSED }),+ makeReport('4'),+ ],+ },+ ],+ },+ })+ initKeaTests()+ logic = reportListLogic({+ sectionKey: 'monitoring',+ listParams: INBOX_REPORT_SECTION_LIST_PARAMS['monitoring'],+ })+ logic.mount()+ logic.actions.ensureLoaded()+ await expectLogic(logic).toFinishAllListeners()+ })++ afterEach(() => logic.unmount())++ it('counts only the rows whose pull request is still open', () => {+ expect(logic.values.openPrReportIds).toEqual(['1'])+ })+ })})diff --git a/products/signals/frontend/inbox/logics/reportListLogic.ts b/products/signals/frontend/inbox/logics/reportListLogic.tsindex 5ec44967d9b7..03deaa2aecb4 100644--- a/products/signals/frontend/inbox/logics/reportListLogic.ts+++ b/products/signals/frontend/inbox/logics/reportListLogic.ts@@ -6,6 +6,7 @@ import { lemonToast } from '@posthog/lemon-ui'import api, { CountedPaginatedResponse } from 'lib/api'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'+import { derivePrState } from 'lib/signals/prState'import { userLogic } from 'scenes/userLogic'import type { UserType } from '~/types'@@ -29,6 +30,7 @@ import { isInboxRedesignEnabled } from '../utils/inboxRedesign'import { inboxBulkActionsLogic } from './inboxBulkActionsLogic'import { buildSignalReportListOrdering, inboxFiltersLogic } from './inboxFiltersLogic'import type { InboxFilterState, InboxSortDirection, InboxSortField } from './inboxFiltersLogic'+import { prCiStatusLogic } from './prCiStatusLogic'const PAGE_SIZE = 50@@ -155,6 +157,7 @@ export interface reportListLogicValues {scope: InboxScope} | nullloadedQueryKey: string | null+ openPrReportIds: string[]pageLoadFailed: booleanprimarySectionKey: InboxReportSectionKeyreports: SignalReport[]@@ -200,6 +203,13 @@ export interface reportListLogicActions {toggleSourceProduct: (source: string) => {source: string} // inboxFiltersLogic+ trackReports: (+ source: string,+ reportIds: string[]+ ) => {+ reportIds: string[]+ source: string+ } // prCiStatusLogicdismissReport: (reportId: string,dismissal: DismissalFeedback@@ -301,6 +311,7 @@ export interface reportListLogicMeta {reports: (reportsResponse: ReportListResponse | null) => SignalReport[]hasMore: (reportsResponse: ReportListResponse | null) => booleanisLoaded: (reportsResponse: ReportListResponse | null) => boolean+ openPrReportIds: (reports: SignalReport[]) => string[]totalCount: (reportsResponse: ReportListResponse | null) => number | nullloadedQueryKey: (reportsResponse: ReportListResponse | null) => string | nullloadedContext: (reportsResponse: ReportListResponse | null) => {@@ -365,6 +376,8 @@ export const reportListLogic = kea<reportListLogicType>(['setFilters','clearFilters',],+ prCiStatusLogic,+ ['trackReports'],],})),@@ -532,6 +545,19 @@ export const reportListLogic = kea<reportListLogicType>([(s) => [s.reportsResponse],(reportsResponse: ReportListResponse | null): boolean => reportsResponse !== null,],+ // The loaded rows whose pull request is still open, so the pill can say whether CI is red.+ // A merged or closed pull request is left out: its checks are history, not something to act on.+ openPrReportIds: [+ (s) => [s.reports],+ (reports: SignalReport[]): string[] =>+ reports+ .filter(+ (report) =>+ !!report.implementation_pr_url &&+ derivePrState(report.status, report.implementation_pr_merged === true) === 'open'+ )+ .map((report) => report.id),+ ],// Total matching the *loaded* results — from the same response, so it can never be stale// relative to `reports` the way the separately-loaded badge `count` can (filter/refresh races).totalCount: [@@ -557,6 +583,11 @@ export const reportListLogic = kea<reportListLogicType>([}),listeners(({ actions, values, props }) => ({+ // Announce this section's open pull requests so their CI state is resolved in one batch. Both+ // loaders report: the first page and each appended page bring rows that need painting. An+ // empty announcement matters too, because it retires the rows a narrowed filter dropped.+ loadReportsSuccess: () => actions.trackReports(props.sectionKey, values.openPrReportIds),+ loadMoreReportsSuccess: () => actions.trackReports(props.sectionKey, values.openPrReportIds),// First For-you count for the primary section: if the user has no reports suggested to// them, default to Entire project so they don't land on an empty inbox. Only when they haven't// picked a scope themselves, and only once the user's uuid has resolved (so the count isdiff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yamlindex e94a4ee85a7a..bd580348b1b7 100644--- a/products/signals/mcp/tools.yaml+++ b/products/signals/mcp/tools.yaml@@ -953,6 +953,9 @@ tools:signals-reports-feedback-create:operation: signals_reports_feedback_createenabled: false+ signals-reports-pr-ci-statuses:+ operation: signals_reports_pr_ci_statuses+ enabled: falsesignals-reports-refund-create:operation: signals_reports_refund_createenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 840a3ac485c9..13bc408c92e9 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -71353,6 +71353,45 @@ export namespace Schemas {readonly checks: readonly PullRequestCheck[];}+ /**+ * * `passing` - Passing+ * * `failing` - Failing+ * * `pending` - Pending+ * * `none` - No checks+ */+ export type PullRequestCiStatusEnum = typeof PullRequestCiStatusEnum[keyof typeof PullRequestCiStatusEnum];+++ export const PullRequestCiStatusEnum = {+ Passing: 'passing',+ Failing: 'failing',+ Pending: 'pending',+ None: 'none',+ } as const;++ /**+ * The CI rollup of one report's implementation pull request.+ */+ export interface PullRequestCiStatus {+ /** Report whose implementation pull request this status describes. */+ readonly report_id: string;+ /** Rollup of the pull request's checks on its head commit: 'passing' (nothing failed), 'failing', 'pending' (checks are still running), or 'none' (the head commit has no checks).+ *+ * * `passing` - Passing+ * * `failing` - Failing+ * * `pending` - Pending+ * * `none` - No checks */+ readonly ci_status: PullRequestCiStatusEnum;+ }++ /**+ * Response for the batch PR CI status endpoint, for painting CI state onto a list of reports.+ */+ export interface PullRequestCiStatusesResponse {+ /** One entry per requested report whose CI state resolved. Reports without an open implementation pull request, and reports GitHub could not answer for, are left out. */+ readonly statuses: readonly PullRequestCiStatus[];+ }+/*** * `LEFT` - LEFT* * `RIGHT` - RIGHT@@ -99639,6 +99678,13 @@ export namespace Schemas {offset?: number;};+ export type SignalsReportsPrCiStatusesParams = {+ /**+ * Comma-separated report UUIDs to resolve CI state for, at most 100 per request.+ */+ report_ids: string;+ };+export type SignalsScoutConfigListParams = {/*** Comma-separated tags, e.g. `revenue,on-call`. Returns the scouts carrying at least one of them. Values are normalized the same way stored tags are, so `On Call` matches `on-call`. Omit for the whole fleet.