: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): sort the inbox by ranking model probability, with a created-in window (#110083)
posthog[bot]1fe468a91e96
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 502a3d034133..6aa79c32d9d5 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -5022,6 +5022,8 @@ const api = {count_only?: 'true' | 'false'/** false skips the ClickHouse lookup for `source_products` and `scout_name`, which then come back empty. */include_source_metadata?: 'true' | 'false'+ /** ISO 8601 datetime. Keeps reports created at or after it. */+ created_after?: string}): Promise<CountedPaginatedResponse<SignalReport>> {return await new ApiRequest().signalReports().withQueryString(params).get()},diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex ad329df5fa22..feb153be6e75 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -355,9 +355,11 @@ export const FEATURE_FLAGS = {HIDE_EVENTS_IN_QUERY_BUILDERS: 'hide-events-in-query-builders', // owner: #team-feature-flags, kill switch for hiding events marked hidden_in_query_builders from insight/cohort/destination pickersHOGQL_WAREHOUSE_ACCESS_CONTROL: 'hogql-warehouse-access-control', // owner: @a-lider #team-platform-features, gates per-object access control for warehouse tables and viewsIDENTITY_MATCHING: 'identity-matching', // owner: @fercgomes #team-growth, gates new identity matching scene on marketing analytics+ INBOX_MODEL_SORT: 'inbox-model-sort', // owner: #team-self-driving, gates the staff-only ranking model sort options and the probability tag on inbox cardsINBOX_REDESIGN: 'inbox-redesign', // owner: #team-self-driving, gates the inbox redesign: report sections, triage mode, the Settings tab, and scout cardsINBOX_SELF_DRIVING_EMPTY_STATE: 'inbox-self-driving-empty-state',INBOX_SLACK_NOTIFICATIONS: 'inbox-slack-notifications', // owner: #team-self-driving, gates the Slack notifications config card in the inbox+ INBOX_TIME_WINDOW: 'inbox-time-window', // owner: #team-self-driving, gates the created-in window filter on the inbox report listINSIGHT_DRAG_TO_ZOOM: 'insight-drag-to-zoom', // owner: @sampennington #team-product-analytics, gates x-axis drag-to-zoom on insight charts (trends today, SQL to follow)INSIGHT_EXPORT_NUDGE: 'insight-export-nudge', // owner: #team-analytics-platform multivariate=control,test, nudges people who just exported an insight toward a recurring subscriptionINSIGHT_SUBSCRIBE_PROMINENT_BUTTON: 'insight-subscribe-prominent-button', // owner: @mattp #team-analytics-platform multivariate=control,testdiff --git a/products/signals/backend/test/test_signal_report_api.py b/products/signals/backend/test/test_signal_report_api.pyindex 139f883ba306..4f6a183750aa 100644--- a/products/signals/backend/test/test_signal_report_api.py+++ b/products/signals/backend/test/test_signal_report_api.py@@ -1058,6 +1058,54 @@ class TestSignalReportListAPI(APIBaseTest):ids = [r["id"] for r in response.json()["results"]]assert ids.index(str(high_candidate.id)) < ids.index(str(low_ready.id))+ @parameterized.expand([("descending", "-ranking_pr_merged"), ("ascending", "ranking_pr_merged")])+ def test_ranking_ordering_sorts_by_the_served_head_with_unscored_last(self, _name, ordering):+ self.user.is_staff = True+ self.user.save()+ low = self._create_report(title="Low")+ high = self._create_report(title="High")+ unscored = self._create_report(title="Unscored")+ no_head = self._create_report(title="No head")+ self._ranking_score_artefact(low, scores={"pr_merged": 0.1, "open": 0.9})+ self._ranking_score_artefact(high, scores={"pr_merged": 0.7, "open": 0.1})+ self._ranking_score_artefact(no_head, scores={"open": 0.5})+ stale = self._ranking_score_artefact(low, scores={"pr_merged": 0.99})+ SignalReportArtefact.objects.filter(pk=stale.pk).update(created_at=timezone.now() - timedelta(days=1))+ bad_latest = self._create_report(title="Bad latest")+ older_valid = self._ranking_score_artefact(bad_latest, scores={"pr_merged": 0.99})+ SignalReportArtefact.objects.filter(pk=older_valid.pk).update(created_at=timezone.now() - timedelta(days=1))+ self._ranking_score_artefact(bad_latest, content="not json")++ response = self.client.get(self._list_url(status="ready", ordering=f"{ordering},status,-updated_at"))+ assert response.status_code == status.HTTP_200_OK+ ids = [r["id"] for r in response.json()["results"]]+ scored = [str(high.id), str(low.id)] if ordering.startswith("-") else [str(low.id), str(high.id)]+ assert ids[:2] == scored+ assert set(ids[2:]) == {str(unscored.id), str(no_head.id), str(bad_latest.id)}++ @parameterized.expand(+ [+ ("ordering", {"ordering": "-ranking_open,status"}, "ordering"),+ ("created_after", {"created_after": "last week"}, "created_after"),+ ]+ )+ def test_list_rejects_invalid_params_with_400(self, _name, query, attr):+ self.user.is_staff = False+ self.user.save()+ response = self.client.get(self._list_url(**query))+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json()["attr"] == attr++ def test_created_after_keeps_reports_created_since(self):+ recent = self._create_report(title="Recent")+ old = self._create_report(title="Old")+ SignalReport.objects.filter(pk=old.pk).update(created_at=timezone.now() - timedelta(days=5))+ cutoff = (timezone.now() - timedelta(days=3)).isoformat()++ response = self.client.get(self._list_url(created_after=cutoff, sort="newest"))+ assert response.status_code == status.HTTP_200_OK+ assert [r["id"] for r in response.json()["results"]] == [str(recent.id)]+@parameterized.expand([("immediately_actionable_before_not_actionable", "immediately_actionable", "not_actionable"),diff --git a/products/signals/backend/views.py b/products/signals/backend/views.pyindex 09adad3e4b54..e874ed567a87 100644--- a/products/signals/backend/views.py+++ b/products/signals/backend/views.py@@ -17,6 +17,7 @@ from django.db.models import (Count,Exists,F,+ FloatField,Func,IntegerField,JSONField,@@ -28,6 +29,7 @@ from django.db.models import (Value,When,)+from django.db.models.expressions import OrderByfrom django.db.models.functions import Cast, Coalescefrom django.utils import timezone@@ -1112,6 +1114,17 @@ class SignalReportViewSet("created_at": "created_at","updated_at": "updated_at","id": "id",+ "ranking_pr_merged": "ranking_pr_merged_score",+ "ranking_pr_created": "ranking_pr_created_score",+ "ranking_action": "ranking_action_score",+ "ranking_open": "ranking_open_score",+ }+ # Ordering field to the outcome head it reads from the served model of the latest ranking score.+ _RANKING_ORDERING_HEADS: dict[str, str] = {+ "ranking_pr_merged": "pr_merged",+ "ranking_pr_created": "pr_created",+ "ranking_action": "action",+ "ranking_open": "open",}@extend_schema(request=ReportReadStateRequestSerializer, responses=ReportReadStateResponseSerializer)@@ -1165,6 +1178,7 @@ class SignalReportViewSet(qs = self._annotate_channel_id(qs)qs = self._apply_signal_report_status_filter(qs)qs = self._apply_signal_report_search_filter(qs)+ qs = self._apply_signal_report_created_after_filter(qs)unread = self.request.query_params.get("unread")if unread is not None:if unread not in {"true", "false"}:@@ -1197,6 +1211,8 @@ class SignalReportViewSet(if self._needs_priority_annotation():qs = self._annotate_signal_report_priority(qs)qs = self._apply_signal_report_priority_filter(qs)+ if self.action == "list":+ qs = self._annotate_signal_report_ranking(qs)qs = self._prefetch_signal_report_priority_artefacts(qs)if self.action != "bulk_state":# `bulk_state` answers with one outcome per id, never a serialized report, and the list@@ -1353,6 +1369,16 @@ class SignalReportViewSet(return querysetreturn queryset.filter(Q(title__icontains=search) | Q(summary__icontains=search))+ def _apply_signal_report_created_after_filter(self, queryset):+ raw = self.request.query_params.get("created_after")+ if not raw:+ return queryset+ try:+ created_after = serializers.DateTimeField().to_internal_value(raw)+ except serializers.ValidationError:+ raise serializers.ValidationError({"created_after": "Use an ISO 8601 datetime."})+ return queryset.filter(created_at__gte=created_after)+def _apply_signal_report_source_product_filter(self, queryset):source_product_filter = self.request.query_params.get("source_product")if not source_product_filter:@@ -1699,6 +1725,60 @@ class SignalReportViewSet())+ def _annotate_signal_report_ranking(self, queryset):+ # `ordering=ranking_<head>` sorts by the served model's probability for that head, read from+ # the latest ranking_score artefact as `results -> <served_key> -> scores -> <head>`. Only+ # the heads the ordering names are annotated, because each one is a correlated subquery.+ # A value that is not a JSON number reads as NULL, so one bad row cannot fail the list.+ # The guard is in the CASE, not the filter: the latest artefact decides, as it does for the+ # `ranking` field, so a bad latest row makes the report unscored rather than older-scored.+ ordered_fields = {clause.lstrip("-") for clause in self._parse_signal_report_ordering()}+ for field, head in self._RANKING_ORDERING_HEADS.items():+ annotation = self._SIGNAL_REPORT_ORDERING_FIELDS[field]+ if annotation not in ordered_fields:+ continue+ content = Cast(F("content"), output_field=JSONField())+ served_key = Func(+ content, Value("served_key"), function="jsonb_extract_path_text", output_field=CharField()+ )+ latest_score = Subquery(+ SignalReportArtefact.objects.filter(+ report_id=OuterRef("id"),+ type=SignalReportArtefact.ArtefactType.RANKING_SCORE,+ )+ .order_by("-created_at")+ .annotate(+ _score=Case(+ When(+ content__startswith="{",+ then=Func(+ content,+ Value("results"),+ served_key,+ Value("scores"),+ Value(head),+ function="jsonb_extract_path",+ output_field=JSONField(),+ ),+ ),+ default=Value(None),+ output_field=JSONField(),+ ),+ )+ .annotate(_score_type=Func(F("_score"), function="jsonb_typeof", output_field=CharField()))+ .annotate(+ _score_value=Case(+ When(_score_type="number", then=Cast(F("_score"), output_field=FloatField())),+ default=Value(None),+ output_field=FloatField(),+ )+ )+ .values("_score_value")[:1],+ output_field=FloatField(),+ )+ queryset = queryset.annotate(**{annotation: latest_score})+ return queryset+def _needs_priority_annotation(self) -> bool:# The priority value is a correlated subquery too, and the serializer renders priority from# the prefetched artefacts instead, so only a priority filter or a priority sort needs it.@@ -1803,6 +1883,9 @@ class SignalReportViewSet(db_field = self._SIGNAL_REPORT_ORDERING_FIELDS.get(name)if db_field is None:continue+ if name in self._RANKING_ORDERING_HEADS and not self.request.user.is_staff:+ # The serializer hides ranking scores from non-staff users, and the order would leak them.+ raise serializers.ValidationError({"ordering": f"Ordering by {name} is only available to staff."})clause = f"-{db_field}" if descending else db_fieldclauses.append(clause)return clauses@@ -1832,7 +1915,18 @@ class SignalReportViewSet(has_id = any((c[1:] if c.startswith("-") else c) == "id" for c in clauses)if not has_id:clauses = [*clauses, "id"]- return queryset.order_by(*clauses)+ ranking_annotations = {self._SIGNAL_REPORT_ORDERING_FIELDS[field] for field in self._RANKING_ORDERING_HEADS}+ order_by: list[str | OrderBy] = []+ for clause in clauses:+ name = clause.lstrip("-")+ if name in ranking_annotations:+ # Unscored reports sort after every scored report, in both directions.+ order_by.append(+ F(name).desc(nulls_last=True) if clause.startswith("-") else F(name).asc(nulls_last=True)+ )+ else:+ order_by.append(clause)+ return queryset.order_by(*order_by)@staticmethoddef _get_github_login(user) -> str | None:@@ -2178,9 +2272,19 @@ class SignalReportViewSet(description=("Comma-separated ordering clauses. Each clause is a field name optionally prefixed with '-' ""for descending. Allowed fields: status, is_suggested_reviewer, signal_count, total_weight, "- "priority, created_at, updated_at, id. Defaults to '-is_suggested_reviewer,status,-updated_at'."+ "priority, created_at, updated_at, id, ranking_pr_merged, ranking_pr_created, ranking_action, "+ "ranking_open. Defaults to '-is_suggested_reviewer,status,-updated_at'. The ranking_* fields "+ "sort by the served ranking model's probability for that outcome head, with unscored reports "+ "last in either direction. They are staff only: other users get a 400."),),+ OpenApiParameter(+ name="created_after",+ type=OpenApiTypes.DATETIME,+ location=OpenApiParameter.QUERY,+ required=False,+ description="ISO 8601 datetime. Keeps reports created at or after this time.",+ ),OpenApiParameter(name="task_id",type=OpenApiTypes.UUID,diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex 1de27af3c108..6025736ed4ab 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -6646,6 +6646,10 @@ export type SignalsReportsListParams = {* Return the filtered total with an empty results page. Skips report ordering, serialization, and decorative metadata lookups. Defaults to false.*/count_only?: boolean+ /**+ * ISO 8601 datetime. Keeps reports created at or after this time.+ */+ created_after?: string/*** Filter reports by whether an implementation pull request is attached. 'true' keeps only reports with a PR; 'false' keeps only those without. Pair with count_only=true to return only the filtered total.*/@@ -6667,7 +6671,7 @@ export type SignalsReportsListParams = {*/offset?: number/**- * Comma-separated ordering clauses. Each clause is a field name optionally prefixed with '-' for descending. Allowed fields: status, is_suggested_reviewer, signal_count, total_weight, priority, created_at, updated_at, id. Defaults to '-is_suggested_reviewer,status,-updated_at'.+ * Comma-separated ordering clauses. Each clause is a field name optionally prefixed with '-' for descending. Allowed fields: status, is_suggested_reviewer, signal_count, total_weight, priority, created_at, updated_at, id, ranking_pr_merged, ranking_pr_created, ranking_action, ranking_open. Defaults to '-is_suggested_reviewer,status,-updated_at'. The ranking_* fields sort by the served ranking model's probability for that outcome head, with unscored reports last in either direction. They are staff only: other users get a 400.*/ordering?: string/**diff --git a/products/signals/frontend/inbox/components/InboxReportList.tsx b/products/signals/frontend/inbox/components/InboxReportList.tsxindex 084cab47058d..2d27998112ca 100644--- a/products/signals/frontend/inbox/components/InboxReportList.tsx+++ b/products/signals/frontend/inbox/components/InboxReportList.tsx@@ -178,6 +178,9 @@ function InboxReportListInner({ tabKey, Card, emptyState }: InboxReportListPropstotalCount,hasActiveFilters: loadedContext.hasActiveFilters,scope: loadedContext.scope,+ sortField: loadedContext.sortField,+ sortDirection: loadedContext.sortDirection,+ createdWindow: loadedContext.createdWindow,})}, [listVisible, isLoaded, totalCount, reports, tabKey, loadedQueryKey, loadedContext])diff --git a/products/signals/frontend/inbox/components/cards/ReportCard.test.tsx b/products/signals/frontend/inbox/components/cards/ReportCard.test.tsxindex f83854b1aab8..7d90391e9053 100644--- a/products/signals/frontend/inbox/components/cards/ReportCard.test.tsx+++ b/products/signals/frontend/inbox/components/cards/ReportCard.test.tsx@@ -369,6 +369,44 @@ describe('ReportCard', () => {expect(container.querySelector('[data-attr="report-card-impact-metric"]')).not.toBeNull()})+ it.each([+ ['with the impact column', true, 'ranking_pr_merged', '41% merge'],+ ['without the impact column', false, 'ranking_action', '6.2% action'],+ ] as const)('shows the active head probability in the meta row %s', (_name, impactColumn, sortField, tagText) => {+ // The harness renders a card for every test; these assert against their own.+ cleanup()+ enableRedesign(impactColumn)+ const report = makeReport('r-2', {+ metrics: [makeMetric()],+ ranking: {+ served_key: 'report_embeddings@2026-09-30',+ model_name: 'report_embeddings',+ model_version: '2026-09-30',+ manifest_version: 'manifest',+ scored_at: '2026-09-30T12:00:00Z',+ scores: { pr_merged: 0.41, action: 0.062 },+ readable_heads: ['action', 'pr_merged'],+ },+ })+ const { container } = render(<ReportCard report={report} rankingSortField={sortField} />)++ const tag = screen.getByText(tagText)+ const impactMetric = container.querySelector('[data-attr="report-card-impact-metric"]')+ expect(impactMetric !== null).toBe(impactColumn)+ expect(impactMetric?.contains(tag) ?? false).toBe(false)+ })++ it('marks an unscored report under a model sort and adds no tag under a time sort', () => {+ // The harness renders a card for every test; these assert against their own.+ cleanup()+ enableRedesign()+ const { rerender } = render(<ReportCard report={makeReport('r-2')} rankingSortField="ranking_pr_merged" />)+ expect(screen.getByText('Not scored')).toBeInTheDocument()++ rerender(<ReportCard report={makeReport('r-2')} />)+ expect(screen.queryByText('Not scored')).not.toBeInTheDocument()+ })+it('does not show a list metric without a stored snapshot, under the legacy design, or with the metrics flag off', () => {const report = makeReport('r-2', { metrics: [makeMetric({ value: null, value_at: null })] })diff --git a/products/signals/frontend/inbox/components/cards/ReportCard.tsx b/products/signals/frontend/inbox/components/cards/ReportCard.tsxindex f83496d4fc39..40c7c695368d 100644--- a/products/signals/frontend/inbox/components/cards/ReportCard.tsx+++ b/products/signals/frontend/inbox/components/cards/ReportCard.tsx@@ -12,6 +12,7 @@ import { ScoutLink } from 'lib/signals/ScoutLink'import { scoutDisplayName } from 'lib/signals/signalCardSourceLine'import { PrBadge } from 'lib/signals/SignalReportPrBadge'+import type { InboxRankingSortField } from '../../logics/inboxFiltersLogic'import { useReportCiStatus } from '../../logics/prCiStatusLogic'import {INBOX_SECTION_LEGACY_TAB,@@ -41,6 +42,7 @@ import {} from '../badges/sourceProductIcons'import { inboxCardRowClassName } from './inboxCardRowClassName'import { ReportCardImpactMetric } from './ReportCardImpactMetric'+import { ReportCardRankingTag } from './ReportCardRankingTag'import { useReportCardSelection } from './useReportCardSelection'import { useReportDismiss } from './useReportDismiss'@@ -122,6 +124,7 @@ function ReportCardRaw({backUrl,preview = false,selectable = false,+ rankingSortField = null,}: {report: SignalReportsectionKey?: InboxReportSectionKey@@ -136,6 +139,8 @@ function ReportCardRaw({preview?: boolean/** Offer multi-select on this row: press and hold and modifier clicks. */selectable?: boolean+ /** The active model sort, if any. The meta row then shows the report's probability for that head. */+ rankingSortField?: InboxRankingSortField | null}): JSX.Element {// Keyed on status, not the section: the legacy Archive tab lists dismissed and resolved rows// through one section key, and the two need different affordances.@@ -290,6 +295,7 @@ function ReportCardRaw({</Tooltip>)}<SignalReportBillingBadge report={report} />+ {rankingSortField && <ReportCardRankingTag report={report} sortField={rankingSortField} />}{!showImpactColumn && (<TZLabeltime={report.updated_at ?? report.created_at}diff --git a/products/signals/frontend/inbox/components/cards/ReportCardRankingTag.tsx b/products/signals/frontend/inbox/components/cards/ReportCardRankingTag.tsxnew file mode 100644index 000000000000..b252261677a5--- /dev/null+++ b/products/signals/frontend/inbox/components/cards/ReportCardRankingTag.tsx@@ -0,0 +1,77 @@+import clsx from 'clsx'++import { LemonTag, Tooltip } from '@posthog/lemon-ui'++import { RANKING_HEAD_LABELS, RANKING_SORT_HEADS } from '../../filterOptions'+import type { InboxRankingSortField } from '../../logics/inboxFiltersLogic'+import { SignalReport } from '../../types'++/** No decimals at 10% and above. Heads such as `action` have low base rates, so one decimal below 10%. */+export function formatRankingProbability(probability: number): string {+ const percent = probability * 100+ const oneDecimal = Math.round(percent * 10) / 10+ return oneDecimal >= 10 ? `${Math.round(percent)}%` : `${oneDecimal.toFixed(1)}%`+}++function RankingTooltip({+ ranking,+ head,+}: {+ ranking: NonNullable<SignalReport['ranking']>+ head: string+}): JSX.Element {+ const heads = [head, ...ranking.readable_heads.filter((name) => name !== head)].filter(+ (name) => typeof ranking.scores[name] === 'number'+ )+ return (+ <div className="flex min-w-56 flex-col gap-1 text-xs">+ {heads.map((name) => {+ const probability = ranking.scores[name]+ return (+ <div key={name} className={clsx('flex items-center gap-2', name === head && 'font-bold')}>+ <span className="w-28 shrink-0">{RANKING_HEAD_LABELS[name] ?? name}</span>+ <span className="h-1.5 flex-1 overflow-hidden rounded-full bg-fill-tertiary">+ <span+ className="block h-full rounded-full bg-current"+ // oxlint-disable-next-line react/forbid-dom-props+ style={{ width: `${Math.round(probability * 100)}%` }}+ />+ </span>+ <span className="w-10 shrink-0 text-right tabular-nums">+ {formatRankingProbability(probability)}+ </span>+ </div>+ )+ })}+ <div className="mt-1 border-t border-primary pt-1 font-mono text-muted">+ {ranking.model_name}@{ranking.model_version}+ </div>+ </div>+ )+}++/** The active model sort's probability for one report, in the card's meta row. */+export function ReportCardRankingTag({+ report,+ sortField,+}: {+ report: SignalReport+ sortField: InboxRankingSortField+}): JSX.Element {+ const { head, tagLabel } = RANKING_SORT_HEADS[sortField]+ const probability = report.ranking?.scores[head]+ if (!report.ranking || typeof probability !== 'number') {+ return (+ <LemonTag size="small" type="muted" data-attr="inbox-ranking-tag">+ Not scored+ </LemonTag>+ )+ }+ return (+ <Tooltip title={<RankingTooltip ranking={report.ranking} head={head} />}>+ <LemonTag size="small" className="cursor-help tabular-nums" data-attr="inbox-ranking-tag">+ {formatRankingProbability(probability)} {tagLabel}+ </LemonTag>+ </Tooltip>+ )+}diff --git a/products/signals/frontend/inbox/components/shell/InboxReportFilters.tsx b/products/signals/frontend/inbox/components/shell/InboxReportFilters.tsxindex bcb8c230b1f7..6e63816d2043 100644--- a/products/signals/frontend/inbox/components/shell/InboxReportFilters.tsx+++ b/products/signals/frontend/inbox/components/shell/InboxReportFilters.tsx@@ -3,14 +3,17 @@ import { useActions, useValues } from 'kea'import { LemonSelect } from '@posthog/lemon-ui'import {+ INBOX_CREATED_WINDOW_OPTIONS,+ INBOX_MODEL_SORT_OPTIONS,INBOX_PRIORITY_OPTIONS,INBOX_SORT_OPTIONS,inboxPriorityFilterLabel,inboxSortOptionKey,PRIORITY_ACCENT,+ InboxSortOption,PRIORITY_MEANING,} from '../../filterOptions'-import { inboxFiltersLogic } from '../../logics/inboxFiltersLogic'+import { InboxCreatedWindow, inboxFiltersLogic } from '../../logics/inboxFiltersLogic'import { SignalReportPriority } from '../../types'import { InboxStateFilter } from './InboxStateFilter'@@ -33,21 +36,41 @@ const PRIORITY_SELECT_OPTIONS = [// No icons: the trigger reads out the active option, and an icon there would crowd the label the// order is already stated in.-const SORT_SELECT_OPTIONS = INBOX_SORT_OPTIONS.map((option) => ({+const toSortSelectOption = (option: InboxSortOption): { value: string; label: string } => ({value: inboxSortOptionKey(option.field, option.direction),label: option.label,-}))+})+const SORT_SELECT_OPTIONS = INBOX_SORT_OPTIONS.map(toSortSelectOption)+const SORT_SELECT_SECTIONS_WITH_MODEL = [+ { options: SORT_SELECT_OPTIONS },+ { title: 'Model', options: INBOX_MODEL_SORT_OPTIONS.map(toSortSelectOption) },+]+const ALL_SORT_OPTIONS = [...INBOX_SORT_OPTIONS, ...INBOX_MODEL_SORT_OPTIONS]++const ANY_TIME = null+const CREATED_WINDOW_SELECT_OPTIONS: { value: InboxCreatedWindow | null; label: string }[] = [+ { value: ANY_TIME, label: 'Any time' },+ ...INBOX_CREATED_WINDOW_OPTIONS.map(({ value, label }) => ({ value, label })),+]/**- * What narrows the report list: priority, then report state, then sort order. Filter state is+ * What narrows the report list: priority, then report state, then sort order, then the created-in window. Filter state is* persisted via `inboxFiltersLogic`, and the list reloads on change.** Reviewer scope is deliberately not here. It sits with triage mode on the other side of the row,* because it picks whose inbox this is rather than narrowing the one you are looking at.*/export function InboxReportFilters(): JSX.Element {- const { sortField, sortDirection, priorityFilter } = useValues(inboxFiltersLogic)- const { setSort, setPriorityFilter } = useActions(inboxFiltersLogic)+ const {+ activeSortField,+ activeSortDirection,+ priorityFilter,+ modelSortAvailable,+ timeWindowAvailable,+ createdWindow,+ } = useValues(inboxFiltersLogic)+ const { setSort, setPriorityFilter, setCreatedWindow } = useActions(inboxFiltersLogic)+ const sortOptions = modelSortAvailable ? ALL_SORT_OPTIONS : INBOX_SORT_OPTIONSreturn (<div className="flex flex-wrap items-center gap-2">@@ -64,17 +87,27 @@ export function InboxReportFilters(): JSX.Element {<InboxStateFilter /><LemonSelectsize="small"- value={inboxSortOptionKey(sortField, sortDirection)}+ value={inboxSortOptionKey(activeSortField, activeSortDirection)}onChange={(key) => {- const option = INBOX_SORT_OPTIONS.find((o) => inboxSortOptionKey(o.field, o.direction) === key)+ const option = sortOptions.find((o) => inboxSortOptionKey(o.field, o.direction) === key)if (option) {setSort(option.field, option.direction)}}}- options={SORT_SELECT_OPTIONS}+ options={modelSortAvailable ? SORT_SELECT_SECTIONS_WITH_MODEL : SORT_SELECT_OPTIONS}renderButtonContent={(leaf) => `Sort: ${leaf?.label ?? ''}`}data-attr="inbox-sort"/>+ {timeWindowAvailable && (+ <LemonSelect+ size="small"+ value={createdWindow}+ onChange={(window) => setCreatedWindow(window)}+ options={CREATED_WINDOW_SELECT_OPTIONS}+ renderButtonContent={(leaf) => `Created: ${leaf?.label ?? 'Any time'}`}+ data-attr="inbox-filter-created-window"+ />+ )}</div>)}diff --git a/products/signals/frontend/inbox/components/shell/InboxSearchFilterBar.tsx b/products/signals/frontend/inbox/components/shell/InboxSearchFilterBar.tsxindex f1abec46258e..56ae5f02a026 100644--- a/products/signals/frontend/inbox/components/shell/InboxSearchFilterBar.tsx+++ b/products/signals/frontend/inbox/components/shell/InboxSearchFilterBar.tsx@@ -100,8 +100,14 @@ export function InboxSearchFilterBar({onRefresh,refreshing,}: InboxSearchFilterBarProps): JSX.Element {- const { searchQuery, sortField, sortDirection, sourceProductFilter, scoutFilter, priorityFilter } =- useValues(inboxFiltersLogic)+ const {+ searchQuery,+ activeSortField: sortField,+ activeSortDirection: sortDirection,+ sourceProductFilter,+ scoutFilter,+ priorityFilter,+ } = useValues(inboxFiltersLogic)const { setSearchQuery, setSort, toggleSourceProduct, toggleScout, clearScoutFilter, togglePriority } =useActions(inboxFiltersLogic)const { scoutConfigs } = useValues(scoutFleetLogic)diff --git a/products/signals/frontend/inbox/components/tabs/ReportsTab.test.tsx b/products/signals/frontend/inbox/components/tabs/ReportsTab.test.tsxindex ab91a06e7e9e..a35f18acacb6 100644--- a/products/signals/frontend/inbox/components/tabs/ReportsTab.test.tsx+++ b/products/signals/frontend/inbox/components/tabs/ReportsTab.test.tsx@@ -252,6 +252,7 @@ describe('ReportsTab', () => {sortField: 'priority',sortDirection: 'asc',searchQuery: '',+ createdWindow: null,})render(<ReportsTab />)diff --git a/products/signals/frontend/inbox/components/tabs/ReportsTab.tsx b/products/signals/frontend/inbox/components/tabs/ReportsTab.tsxindex 300837ed0932..10ca9f72e70f 100644--- a/products/signals/frontend/inbox/components/tabs/ReportsTab.tsx+++ b/products/signals/frontend/inbox/components/tabs/ReportsTab.tsx@@ -1,18 +1,20 @@import { useMountedLogic, useValues } from 'kea'-import { JSX, memo, useCallback, useEffect, useRef } from 'react'+import { Fragment, JSX, memo, useCallback, useEffect, useRef } from 'react'import { IconNotebook } from '@posthog/icons'-import { LemonButton } from '@posthog/lemon-ui'+import { LemonButton, LemonDivider } from '@posthog/lemon-ui'import { KeyboardShortcut } from 'lib/components/KeyboardShortcut/KeyboardShortcut'import { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { urls } from 'scenes/urls'+import { isRankingSortField } from '../../filterOptions'import { captureInboxViewed } from '../../inboxAnalytics'import { inboxSceneLogic } from '../../inboxSceneLogic'import { inboxTaskKickoffLogic } from '../../inboxTaskKickoffLogic'import { inboxFiltersLogic, isDefaultStateFilter } from '../../logics/inboxFiltersLogic'+import type { InboxRankingSortField } from '../../logics/inboxFiltersLogic'import { reportListLogic, sectionListLogicProps } from '../../logics/reportListLogic'import {INBOX_SCOPE_ENTIRE_PROJECT,@@ -22,6 +24,7 @@ import {SignalReport,} from '../../types'import { mergeReportRows, selectedFlatListSections } from '../../utils/flatReportList'+import { rankingSortScore } from '../../utils/reportOrdering'import { CardSkeleton } from '../cards/CardSkeleton'import { ReportCard } from '../cards/ReportCard'import { ReportContextMenu } from '../cards/ReportContextMenu'@@ -161,9 +164,11 @@ function useInboxViewedEvent(sections: Record<CountedSectionKey, SectionListStatconst ReportRow = memo(function ReportRow({report,sectionKey,+ rankingSortField,}: {report: SignalReportsectionKey: InboxReportSectionKey+ rankingSortField: InboxRankingSortField | null}): JSX.Element {return (<ReportContextMenu report={report} sectionKey={sectionKey}>@@ -171,6 +176,7 @@ const ReportRow = memo(function ReportRow({report={report}sectionKey={sectionKey}selectable+ rankingSortField={rankingSortField}onRestore={() =>reportListLogic(sectionListLogicProps(sectionKey)).actions.restoreReport(report.id, 'list_row')}@@ -224,7 +230,9 @@ export function ReportsTab(): JSX.Element {// The row context menus dispatch to this logic and unmount when a menu closes; pinning it here// keeps an in-flight create-PR listener alive past the click that closed the menu.useMountedLogic(inboxTaskKickoffLogic)- const { hasActiveFilters, visibleStateFilter, scope, sortField, sortDirection } = useValues(inboxFiltersLogic)+ const { hasActiveFilters, visibleStateFilter, scope, activeSortField, activeSortDirection } =+ useValues(inboxFiltersLogic)+ const rankingSortField = isRankingSortField(activeSortField) ? activeSortField : nullconst sections = useSectionStates()useInboxViewedEvent(sections)@@ -253,7 +261,11 @@ export function ReportsTab(): JSX.Element {InboxReportSectionKey,SignalReport[]>- const rows = mergeReportRows(reportsBySection, selectedSections, sortField, sortDirection)+ const rows = mergeReportRows(reportsBySection, selectedSections, activeSortField, activeSortDirection)+ // Under a model sort the unscored rows trail the scored ones. A divider marks where they start.+ const firstUnscoredIndex = rankingSortField+ ? rows.findIndex(({ report }) => rankingSortScore(report, rankingSortField) === null)+ : -1useReportImpressions(rows, selectedSections)// Multi-select ranges over this order, and drops any id the merged list no longer holds.useSelectableReportList(rows.map(({ report }) => report.id))@@ -382,8 +394,13 @@ export function ReportsTab(): JSX.Element {)) : (<div className="@container flex flex-col gap-1.5">- {rows.map(({ report, sectionKey }) => (- <ReportRow key={report.id} report={report} sectionKey={sectionKey} />+ {rows.map(({ report, sectionKey }, index) => (+ <Fragment key={report.id}>+ {index > 0 && index === firstUnscoredIndex && (+ <LemonDivider label="Not scored yet" className="my-2 text-xs text-tertiary" />+ )}+ <ReportRow report={report} sectionKey={sectionKey} rankingSortField={rankingSortField} />+ </Fragment>))}{/* Skeleton cards continue the list while the next pages load – sleeker than a spinner. */}{pageLoading && <CardSkeleton count={2} variant="cards" dashed />}diff --git a/products/signals/frontend/inbox/components/useReportImpressions.ts b/products/signals/frontend/inbox/components/useReportImpressions.tsindex b62320c963ec..ac6a013dccbd 100644--- a/products/signals/frontend/inbox/components/useReportImpressions.ts+++ b/products/signals/frontend/inbox/components/useReportImpressions.ts@@ -3,7 +3,7 @@ import { useEffect, useRef } from 'react'import { captureInboxReportsImpressed } from '../inboxAnalytics'import { inboxSceneLogic } from '../inboxSceneLogic'-import { reportListLogic, sectionListLogicProps } from '../logics/reportListLogic'+import { ReportListRequestContext, reportListLogic, sectionListLogicProps } from '../logics/reportListLogic'import { InboxReportSectionKey } from '../types'import type { MergedReportRow } from '../utils/flatReportList'@@ -13,7 +13,7 @@ interface SectionImpressionState {reportsResponseLoading: booleantotalCount: number | nullloadedQueryKey: string | null- loadedContext: { scope: string; hasActiveFilters: boolean } | null+ loadedContext: ReportListRequestContext | null}function useSectionImpressionState(sectionKey: InboxReportSectionKey): SectionImpressionState {@@ -100,6 +100,9 @@ export function useReportImpressions(rows: MergedReportRow[], selectedSections:totalCount: sections[sectionKey].totalCount,hasActiveFilters: context.hasActiveFilters,scope: context.scope,+ sortField: context.sortField,+ sortDirection: context.sortDirection,+ createdWindow: context.createdWindow,})}// `sections` is a fresh object each render; `contextKey` and `settled` already change withdiff --git a/products/signals/frontend/inbox/filterOptions.tsx b/products/signals/frontend/inbox/filterOptions.tsxindex ee161e685550..d4e0203d4d19 100644--- a/products/signals/frontend/inbox/filterOptions.tsx+++ b/products/signals/frontend/inbox/filterOptions.tsx@@ -19,7 +19,12 @@ import {} from '@posthog/icons'import { LemonTagType } from '@posthog/lemon-ui'-import type { InboxSortDirection, InboxSortField } from './logics/inboxFiltersLogic'+import type {+ InboxCreatedWindow,+ InboxRankingSortField,+ InboxSortDirection,+ InboxSortField,+} from './logics/inboxFiltersLogic'import { SignalReportPriority } from './types'import { prettifyScoutSkillName } from './utils/scoutRunsWindow'@@ -79,6 +84,52 @@ export const INBOX_SORT_OPTIONS: InboxSortOption[] = [{ label: 'Oldest first', field: 'created_at', direction: 'asc', icon: <IconClock /> },]+/** Staff-only sorts by the ranking model's served probability for one outcome head. Descending only. */+export const INBOX_MODEL_SORT_OPTIONS: InboxSortOption[] = [+ { label: 'Most likely to merge', field: 'ranking_pr_merged', direction: 'desc', icon: <IconBrain /> },+ { label: 'Most likely to get a PR', field: 'ranking_pr_created', direction: 'desc', icon: <IconBrain /> },+ { label: 'Most likely to need action', field: 'ranking_action', direction: 'desc', icon: <IconBrain /> },+ { label: 'Most likely to be opened', field: 'ranking_open', direction: 'desc', icon: <IconBrain /> },+]++export function isRankingSortField(field: InboxSortField): field is InboxRankingSortField {+ return field.startsWith('ranking_')+}++/** The outcome head each model sort reads, and the short word its card tag uses ("41% merge"). */+export const RANKING_SORT_HEADS: Record<InboxRankingSortField, { head: string; tagLabel: string }> = {+ ranking_pr_merged: { head: 'pr_merged', tagLabel: 'merge' },+ ranking_pr_created: { head: 'pr_created', tagLabel: 'PR' },+ ranking_action: { head: 'action', tagLabel: 'action' },+ ranking_open: { head: 'open', tagLabel: 'open' },+}++/** Display names for the ranking heads in the probability tooltip. Unknown heads show their raw name. */+export const RANKING_HEAD_LABELS: Record<string, string> = {+ pr_merged: 'PR merged',+ pr_created: 'PR created',+ action: 'Needs action',+ open: 'Opened',+ thumbs_up: 'Thumbs up',+ discuss: 'Discussed',+ dismiss_wrong: 'Dismissed as wrong',+ refund: 'Refunded',+ reviewer_fix: 'Reviewer fix',+}++export const INBOX_CREATED_WINDOW_OPTIONS: { value: InboxCreatedWindow; label: string; hours: number }[] = [+ { value: '24h', label: 'Last 24 hours', hours: 24 },+ { value: '3d', label: 'Last 3 days', hours: 3 * 24 },+ { value: '7d', label: 'Last 7 days', hours: 7 * 24 },+ { value: '14d', label: 'Last 14 days', hours: 14 * 24 },+]++/** The `created_after` bound for a window, computed at request time so a long-open tab never sends a stale bound. */+export function createdAfterForWindow(window: InboxCreatedWindow | null, now: number = Date.now()): string | undefined {+ const option = INBOX_CREATED_WINDOW_OPTIONS.find((o) => o.value === window)+ return option ? new Date(now - option.hours * 60 * 60 * 1000).toISOString() : undefined+}+export const INBOX_SOURCE_OPTIONS: { value: string; label: string; icon: JSX.Element }[] = [{ value: 'replay_vision', label: 'Replay vision', icon: <IconEye /> },{ value: 'error_tracking', label: 'Error tracking', icon: <IconBug /> },diff --git a/products/signals/frontend/inbox/inboxAnalytics.test.ts b/products/signals/frontend/inbox/inboxAnalytics.test.tsindex 2c4dfd3f2306..c227c039b942 100644--- a/products/signals/frontend/inbox/inboxAnalytics.test.ts+++ b/products/signals/frontend/inbox/inboxAnalytics.test.ts@@ -115,14 +115,31 @@ describe('inboxAnalytics', () => {captureInboxReportsImpressed({tab: 'reports',reports: [- makeReport({ id: 'a', priority: 'P0', signal_count: 3, is_suggested_reviewer: true }),+ makeReport({+ id: 'a',+ priority: 'P0',+ signal_count: 3,+ is_suggested_reviewer: true,+ ranking: {+ served_key: 'report_embeddings@2026-09-30',+ model_name: 'report_embeddings',+ model_version: '2026-09-30',+ manifest_version: 'manifest',+ scored_at: '2026-09-30T12:00:00Z',+ scores: { pr_merged: 0.4 },+ readable_heads: ['pr_merged'],+ },+ }),makeReport({ id: 'b', priority: null, actionability: null, source_products: ['error_tracking'] }),],ranks: [1, 2],listSize: 2,totalCount: 10,- hasActiveFilters: false,+ hasActiveFilters: true,scope: 'for-you',+ sortField: 'ranking_pr_merged',+ sortDirection: 'desc',+ createdWindow: '7d',})const props = lastCapture(INBOX_EVENTS.REPORTS_IMPRESSED)expect(props).toMatchObject({@@ -130,6 +147,9 @@ describe('inboxAnalytics', () => {list_size: 2,total_count: 10,impression_count: 2,+ sort_field: 'ranking_pr_merged',+ sort_direction: 'desc',+ created_window: '7d',})expect(props?.impressions).toEqual([expect.objectContaining({@@ -138,10 +158,12 @@ describe('inboxAnalytics', () => {priority: 'P0',signal_count: 3,is_suggested_reviewer: true,+ ranking_served_key: 'report_embeddings@2026-09-30',}),expect.objectContaining({report_id: 'b',rank: 2,+ ranking_served_key: null,priority: null,actionability: null,source_products: ['error_tracking'],@@ -213,6 +235,7 @@ describe('inboxAnalytics', () => {stateFilter: ['monitoring'],searchQuery: ' acme checkout crash ',hasActiveFilters: true,+ createdWindow: null,})const props = lastCapture(INBOX_EVENTS.QUERY_CHANGED)expect(props).toMatchObject({diff --git a/products/signals/frontend/inbox/inboxAnalytics.ts b/products/signals/frontend/inbox/inboxAnalytics.tsindex 0cc4165a3df9..94d6cbc10251 100644--- a/products/signals/frontend/inbox/inboxAnalytics.ts+++ b/products/signals/frontend/inbox/inboxAnalytics.ts@@ -177,6 +177,7 @@ export type InboxQueryChange =| 'search'| 'clear'| 'url'+ | 'created_window'/** Surface a scout-management event fired from. Matches the desktop values. */export type ScoutSurface = 'fleet_list' | 'scout_detail' | 'empty_state' | 'replay_vision_scanner'@@ -387,13 +388,21 @@ export function captureInboxReportsImpressed(params: {totalCount: number | nullhasActiveFilters: booleanscope: string+ /** The sort and window the list was requested with, so model-ordered lists can be told apart in training data. */+ sortField: string+ sortDirection: string+ createdWindow: string | null}): void {+ const rankingSort = params.sortField.startsWith('ranking_')captureInboxEvent(INBOX_EVENTS.REPORTS_IMPRESSED, {tab: params.tab,list_size: params.listSize,total_count: params.totalCount,has_active_filters: params.hasActiveFilters,scope: params.scope,+ sort_field: params.sortField,+ sort_direction: params.sortDirection,+ created_window: params.createdWindow,impression_count: params.reports.length,impressions: params.reports.map((report, index) => ({...baseReportProperties(report),@@ -403,6 +412,7 @@ export function captureInboxReportsImpressed(params: {signal_count: report.signal_count,total_weight: report.total_weight,is_suggested_reviewer: report.is_suggested_reviewer,+ ...(rankingSort ? { ranking_served_key: report.ranking?.served_key ?? null } : {}),})),})}@@ -685,6 +695,7 @@ export function captureInboxQueryChanged(params: {stateFilter: string[]searchQuery: stringhasActiveFilters: boolean+ createdWindow: string | null}): void {const search = params.searchQuery.trim()captureInboxEvent(INBOX_EVENTS.QUERY_CHANGED, {@@ -700,6 +711,7 @@ export function captureInboxQueryChanged(params: {has_search: search.length > 0,search_length: search.length,has_active_filters: params.hasActiveFilters,+ created_window: params.createdWindow,})}diff --git a/products/signals/frontend/inbox/inboxSceneLogic.ts b/products/signals/frontend/inbox/inboxSceneLogic.tsindex 433d0760836f..26cbeccd90f4 100644--- a/products/signals/frontend/inbox/inboxSceneLogic.ts+++ b/products/signals/frontend/inbox/inboxSceneLogic.ts@@ -290,8 +290,8 @@ function findReportRank(const rows = mergeReportRows(reportsBySection,selectedFlatListSections(filterValues.visibleStateFilter, isStaff),- filterValues.sortField,- filterValues.sortDirection+ filterValues.activeSortField,+ filterValues.activeSortDirection)const idx = rows.findIndex((row) => row.report.id === id)if (idx >= 0) {diff --git a/products/signals/frontend/inbox/logics/inboxFiltersLogic.test.ts b/products/signals/frontend/inbox/logics/inboxFiltersLogic.test.tsindex 05980edc66f5..1780977a6533 100644--- a/products/signals/frontend/inbox/logics/inboxFiltersLogic.test.ts+++ b/products/signals/frontend/inbox/logics/inboxFiltersLogic.test.ts@@ -1,3 +1,5 @@+import { MOCK_DEFAULT_USER } from 'lib/api.mock'+/* oxlint-disable react-hooks/rules-of-hooks -- useMocks is a test helper, not a React hook */import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'@@ -6,6 +8,7 @@ import posthog from 'posthog-js'import { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { urls } from 'scenes/urls'+import { userLogic } from 'scenes/userLogic'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'@@ -30,6 +33,7 @@ const DEFAULT_STATE: InboxFilterState = {sortField: 'priority',sortDirection: 'asc',searchQuery: '',+ createdWindow: null,}describe('inboxFiltersLogic', () => {@@ -50,6 +54,12 @@ describe('inboxFiltersLogic', () => {it('leads with priority for "Priority first"', () => {expect(buildSignalReportListOrdering('priority', 'asc')).toBe('priority,status,-updated_at')})++ it('leads with the ranking field for a model sort', () => {+ expect(buildSignalReportListOrdering('ranking_pr_merged', 'desc')).toBe(+ '-ranking_pr_merged,status,-updated_at'+ )+ })})describe('filter URL params', () => {@@ -72,6 +82,7 @@ describe('inboxFiltersLogic', () => {sortField: 'created_at',sortDirection: 'desc',searchQuery: 'checkout crash',+ createdWindow: null,},{scope: 'entire-project',@@ -91,6 +102,7 @@ describe('inboxFiltersLogic', () => {// An unchecked-everything selection means every state. It must survive the URL rewrite// that follows each toggle, or hydration would put the default selection straight back.['an explicitly empty state selection', { ...DEFAULT_STATE, stateFilter: [] }, { state: 'all' }],+ ['a created-in window', { ...DEFAULT_STATE, createdWindow: '7d' }, { created: '7d' }],])('round-trips %s through encode/decode', (_name, state, expectedParams) => {expect(filterSearchParams(state)).toEqual(expectedParams)expect(parseFilterSearchParams(expectedParams)).toEqual(state)@@ -116,6 +128,17 @@ describe('inboxFiltersLogic', () => {stateFilter: ['monitoring'],})})++ it.each([+ ['keeps a model sort for a user who can use it', true, 'ranking_pr_merged', 'desc'],+ ['falls back to the default sort for a user who cannot', false, 'priority', 'asc'],+ ] as const)('%s', (_name, modelSortAvailable, sortField, sortDirection) => {+ expect(parseFilterSearchParams({ sort: 'ranking_pr_merged:desc' }, { modelSortAvailable })).toEqual({+ ...DEFAULT_STATE,+ sortField,+ sortDirection,+ })+ })})describe('query-changed telemetry', () => {@@ -179,7 +202,7 @@ describe('inboxFiltersLogic', () => {})})- describe('scout filters', () => {+ describe('filter state', () => {let logic: ReturnType<typeof inboxFiltersLogic.build>beforeEach(() => {@@ -210,5 +233,28 @@ describe('inboxFiltersLogic', () => {searchQuery: 'checkout',})})++ it.each([+ ['keeps a stored model sort for staff with the flag', true, true, 'ranking_pr_merged', 'desc'],+ ['falls back to the default once the flag is off', false, true, 'priority', 'asc'],+ ['falls back to the default for a non-staff user', true, false, 'priority', 'asc'],+ ] as const)('%s', (_name, flagOn, isStaff, activeSortField, activeSortDirection) => {+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.INBOX_MODEL_SORT], {+ [FEATURE_FLAGS.INBOX_MODEL_SORT]: true,+ })+ userLogic.actions.loadUserSuccess({ ...MOCK_DEFAULT_USER, is_staff: true })+ logic.actions.setSort('ranking_pr_merged', 'desc')++ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.INBOX_MODEL_SORT], {+ [FEATURE_FLAGS.INBOX_MODEL_SORT]: flagOn,+ })+ userLogic.actions.loadUserSuccess({ ...MOCK_DEFAULT_USER, is_staff: isStaff })++ expect(logic.values).toMatchObject({+ sortField: 'ranking_pr_merged',+ activeSortField,+ activeSortDirection,+ })+ })})})diff --git a/products/signals/frontend/inbox/logics/inboxFiltersLogic.ts b/products/signals/frontend/inbox/logics/inboxFiltersLogic.tsindex 9769513c1b84..c58e496cd63c 100644--- a/products/signals/frontend/inbox/logics/inboxFiltersLogic.ts+++ b/products/signals/frontend/inbox/logics/inboxFiltersLogic.ts@@ -3,6 +3,7 @@ import { loaders } from 'kea-loaders'import { actionToUrl, router, urlToAction } from 'kea-router'import api from 'lib/api'+import { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'import { isUUIDLike } from 'lib/utils/guards'@@ -11,7 +12,14 @@ import { userLogic } from 'scenes/userLogic'import type { UserType } from '~/types'-import { INBOX_PRIORITY_OPTIONS, INBOX_SORT_OPTIONS, INBOX_SOURCE_OPTIONS } from '../filterOptions'+import {+ INBOX_CREATED_WINDOW_OPTIONS,+ INBOX_MODEL_SORT_OPTIONS,+ INBOX_PRIORITY_OPTIONS,+ INBOX_SORT_OPTIONS,+ INBOX_SOURCE_OPTIONS,+ isRankingSortField,+} from '../filterOptions'import { captureInboxQueryChanged, InboxQueryChange } from '../inboxAnalytics'import { parseTeammateInboxScope } from '../inboxMembership'import {@@ -33,8 +41,14 @@ export interface InboxReviewerOption {email: string}-export type InboxSortField = 'priority' | 'created_at' | 'updated_at'+export type InboxRankingSortField = 'ranking_pr_merged' | 'ranking_pr_created' | 'ranking_action' | 'ranking_open'+export type InboxSortField = 'priority' | 'created_at' | 'updated_at' | InboxRankingSortFieldexport type InboxSortDirection = 'asc' | 'desc'+/** Preset for the created-in window filter. Null means any time. */+export type InboxCreatedWindow = '24h' | '3d' | '7d' | '14d'++/** The window a model sort picks when none is set: the ranking sweep only scores reports from the last 7 days. */+const MODEL_SORT_DEFAULT_WINDOW: InboxCreatedWindow = '7d'const DEFAULT_SORT_FIELD: InboxSortField = 'priority'const DEFAULT_SORT_DIRECTION: InboxSortDirection = 'asc'@@ -58,7 +72,7 @@ export function isDefaultStateFilter(stateFilter: InboxReportSectionKey[]): bool}// Query-param keys that mirror the filter state so a view can be shared via URL.-const FILTER_URL_KEYS = ['scope', 'source', 'scout', 'priority', 'state', 'sort', 'search'] as const+const FILTER_URL_KEYS = ['scope', 'source', 'scout', 'priority', 'state', 'sort', 'search', 'created'] as constconst VALID_SOURCE_VALUES = new Set(INBOX_SOURCE_OPTIONS.map((o) => o.value))const VALID_PRIORITIES = new Set<string>(INBOX_PRIORITY_OPTIONS)@@ -66,6 +80,8 @@ const VALID_STATE_VALUES = new Set<string>(INBOX_REPORT_SECTION_KEYS)// Only the field/direction combinations the Sort control actually offers — validating the field and// direction independently would accept keys like `priority:desc` that have no matching UI option.const VALID_SORT_KEYS = new Set(INBOX_SORT_OPTIONS.map((o) => `${o.field}:${o.direction}`))+const VALID_MODEL_SORT_KEYS = new Set(INBOX_MODEL_SORT_OPTIONS.map((o) => `${o.field}:${o.direction}`))+const VALID_CREATED_WINDOWS = new Set<string>(INBOX_CREATED_WINDOW_OPTIONS.map((o) => o.value))export interface InboxFilterState {scope: InboxScope@@ -76,6 +92,7 @@ export interface InboxFilterState {sortField: InboxSortFieldsortDirection: InboxSortDirectionsearchQuery: string+ createdWindow: InboxCreatedWindow | null}function parseScopeParam(raw: unknown): InboxScope {@@ -124,11 +141,20 @@ function parseScoutParam(raw: unknown): string[] {.filter((v) => v.length > 0)}-/** Decode the filter query params into filter state, ignoring unknown/invalid values and falling back to defaults. */-export function parseFilterSearchParams(searchParams: Record<string, any>): InboxFilterState {+/**+ * Decode the filter query params into filter state, ignoring unknown/invalid values and falling back to defaults.+ * A model sort in a link opened by a user who cannot use it falls back to the default sort.+ */+export function parseFilterSearchParams(+ searchParams: Record<string, any>,+ { modelSortAvailable = false }: { modelSortAvailable?: boolean } = {}+): InboxFilterState {let sortField = DEFAULT_SORT_FIELDlet sortDirection = DEFAULT_SORT_DIRECTION- if (typeof searchParams.sort === 'string' && VALID_SORT_KEYS.has(searchParams.sort)) {+ if (+ typeof searchParams.sort === 'string' &&+ (VALID_SORT_KEYS.has(searchParams.sort) || (modelSortAvailable && VALID_MODEL_SORT_KEYS.has(searchParams.sort)))+ ) {const [field, direction] = searchParams.sort.split(':')sortField = field as InboxSortFieldsortDirection = direction as InboxSortDirection@@ -142,6 +168,9 @@ export function parseFilterSearchParams(searchParams: Record<string, any>): InbosortField,sortDirection,searchQuery: typeof searchParams.search === 'string' ? searchParams.search : '',+ createdWindow: VALID_CREATED_WINDOWS.has(searchParams.created)+ ? (searchParams.created as InboxCreatedWindow)+ : null,}}@@ -194,6 +223,9 @@ export function filterSearchParams(values: InboxFilterState): Record<string, strif (values.searchQuery.trim().length > 0) {params.search = values.searchQuery}+ if (values.createdWindow) {+ params.created = values.createdWindow+ }return params}@@ -237,8 +269,12 @@ export function buildSignalReportListOrdering(field: InboxSortField, direction:export interface inboxFiltersLogicValues {featureFlags: FeatureFlagsSet // featureFlagLogicuser: UserType | null // userLogic+ activeCreatedWindow: InboxCreatedWindow | null+ activeSortDirection: InboxSortDirection+ activeSortField: InboxSortFieldavailableReviewers: InboxReviewerOption[]availableReviewersLoading: boolean+ createdWindow: InboxCreatedWindow | nullhasActiveFilters: booleanhasUserChosenScope: booleanisRedesign: boolean@@ -246,6 +282,7 @@ export interface inboxFiltersLogicValues {label: stringuuid: string} | null+ modelSortAvailable: booleanpriorityFilter: SignalReportPriority[]scope: InboxScopescoutFilter: string[]@@ -254,11 +291,15 @@ export interface inboxFiltersLogicValues {sortField: InboxSortFieldsourceProductFilter: string[]stateFilter: ('dismissed' | 'monitoring' | 'needs-decision' | 'not-actionable' | 'resolved')[]+ timeWindowAvailable: booleanvisibleStateFilter: InboxReportSectionKey[]}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface inboxFiltersLogicActions {+ applyDefaultCreatedWindow: (createdWindow: InboxCreatedWindow) => {+ createdWindow: InboxCreatedWindow+ }applyDefaultScope: (scope: InboxScope) => {scope: InboxScope}@@ -300,6 +341,9 @@ export interface inboxFiltersLogicActions {searchAvailableReviewers: (query: string) => {query: string}+ setCreatedWindow: (createdWindow: InboxCreatedWindow | null) => {+ createdWindow: InboxCreatedWindow | null+ }setFilters: (filters: InboxFilterState) => {filters: InboxFilterState}@@ -347,8 +391,21 @@ export interface inboxFiltersLogicMeta {searchQuery: string,sourceProductFilter: string[],scoutFilter: string[],- priorityFilter: SignalReportPriority[]+ priorityFilter: SignalReportPriority[],+ activeCreatedWindow: InboxCreatedWindow | null) => boolean+ modelSortAvailable: (featureFlags: FeatureFlagsSet, user: UserType | null) => boolean+ activeSortField: (sortField: InboxSortField, modelSortAvailable: boolean) => InboxSortField+ activeSortDirection: (+ sortField: InboxSortField,+ sortDirection: InboxSortDirection,+ modelSortAvailable: boolean+ ) => InboxSortDirection+ timeWindowAvailable: (featureFlags: FeatureFlagsSet) => boolean+ activeCreatedWindow: (+ createdWindow: InboxCreatedWindow | null,+ timeWindowAvailable: boolean+ ) => InboxCreatedWindow | nullisRedesign: (featureFlags: FeatureFlagsSet) => booleanvisibleStateFilter: (stateFilter: ('dismissed' | 'monitoring' | 'needs-decision' | 'not-actionable' | 'resolved')[],@@ -394,6 +451,9 @@ export const inboxFiltersLogic = kea<inboxFiltersLogicType>([applyDefaultScope: (scope: InboxScope) => ({ scope }),setSearchQuery: (searchQuery: string) => ({ searchQuery }),setSort: (field: InboxSortField, direction: InboxSortDirection) => ({ field, direction }),+ setCreatedWindow: (createdWindow: InboxCreatedWindow | null) => ({ createdWindow }),+ // Set by a model sort, not by the user, so it is not a query change of its own.+ applyDefaultCreatedWindow: (createdWindow: InboxCreatedWindow) => ({ createdWindow }),toggleSourceProduct: (source: string) => ({ source }),toggleScout: (scout: string) => ({ scout }),clearScoutFilter: true,@@ -438,14 +498,15 @@ export const inboxFiltersLogic = kea<inboxFiltersLogicType>([change,tab: currentInboxTab(values.isRedesign),scope: values.scope,- sortField: values.sortField,- sortDirection: values.sortDirection,+ sortField: values.activeSortField,+ sortDirection: values.activeSortDirection,sourceProductFilter: values.sourceProductFilter,scoutFilter: values.scoutFilter,priorityFilter: values.priorityFilter,stateFilter: values.stateFilter,searchQuery: values.searchQuery,hasActiveFilters: values.hasActiveFilters,+ createdWindow: values.activeCreatedWindow,})const rememberSelectedTeammate = (): void => {@@ -468,7 +529,13 @@ export const inboxFiltersLogic = kea<inboxFiltersLogicType>([rememberSelectedTeammate()captureQueryChange('scope')},- setSort: () => captureQueryChange('sort'),+ setSort: ({ field }) => {+ if (isRankingSortField(field) && values.timeWindowAvailable && values.createdWindow === null) {+ actions.applyDefaultCreatedWindow(MODEL_SORT_DEFAULT_WINDOW)+ }+ captureQueryChange('sort')+ },+ setCreatedWindow: () => captureQueryChange('created_window'),toggleSourceProduct: () => captureQueryChange('source_product'),toggleScout: () => captureQueryChange('scout'),clearScoutFilter: () => captureQueryChange('scout'),@@ -540,6 +607,16 @@ export const inboxFiltersLogic = kea<inboxFiltersLogicType>([setFilters: (_, { filters }) => filters.sortDirection,},],+ createdWindow: [+ null as InboxCreatedWindow | null,+ { persist: true },+ {+ setCreatedWindow: (_, { createdWindow }) => createdWindow,+ applyDefaultCreatedWindow: (_, { createdWindow }) => createdWindow,+ setFilters: (_, { filters }) => filters.createdWindow,+ clearFilters: () => null,+ },+ ],sourceProductFilter: [[] as string[],{ persist: true },@@ -588,22 +665,57 @@ export const inboxFiltersLogic = kea<inboxFiltersLogicType>([selectors({// Whether any server-side list-narrowing filter is active. Scope and sort are excluded: they- // don't hide reports the way search/source/priority do, and `clearFilters` leaves them+ // don't hide reports the way search/source/priority/created window do, and `clearFilters` leaves them// untouched. The state filter is also excluded: it only narrows which states the flat// Reports list renders (client-side, redesign only), so the surfaces that need it check// `stateFilter` directly.hasActiveFilters: [- (s) => [s.searchQuery, s.sourceProductFilter, s.scoutFilter, s.priorityFilter],+ (s) => [s.searchQuery, s.sourceProductFilter, s.scoutFilter, s.priorityFilter, s.activeCreatedWindow],(searchQuery: string,sourceProductFilter: string[],scoutFilter: string[],- priorityFilter: SignalReportPriority[]+ priorityFilter: SignalReportPriority[],+ activeCreatedWindow: InboxCreatedWindow | null): boolean =>searchQuery.trim().length > 0 ||sourceProductFilter.length > 0 ||scoutFilter.length > 0 ||- priorityFilter.length > 0,+ priorityFilter.length > 0 ||+ activeCreatedWindow !== null,+ ],+ // Staff only, the same rule as the `ranking` field the backend returns.+ modelSortAvailable: [+ (s) => [s.featureFlags, s.user],+ (featureFlags: FeatureFlagsSet, user: UserType | null): boolean =>+ !!featureFlags[FEATURE_FLAGS.INBOX_MODEL_SORT] && !!user?.is_staff,+ ],+ // The sort the list requests and renders with. A model sort persisted while it was available+ // falls back to the default once it is not, because the backend rejects it for non-staff.+ activeSortField: [+ (s) => [s.sortField, s.modelSortAvailable],+ (sortField: InboxSortField, modelSortAvailable: boolean): InboxSortField =>+ isRankingSortField(sortField) && !modelSortAvailable ? DEFAULT_SORT_FIELD : sortField,+ ],+ activeSortDirection: [+ (s) => [s.sortField, s.sortDirection, s.modelSortAvailable],+ (+ sortField: InboxSortField,+ sortDirection: InboxSortDirection,+ modelSortAvailable: boolean+ ): InboxSortDirection =>+ isRankingSortField(sortField) && !modelSortAvailable ? DEFAULT_SORT_DIRECTION : sortDirection,+ ],+ timeWindowAvailable: [+ (s) => [s.featureFlags],+ (featureFlags: FeatureFlagsSet): boolean => !!featureFlags[FEATURE_FLAGS.INBOX_TIME_WINDOW],+ ],+ // The window the list requests with. A stored window does nothing while its flag is off, so+ // a window persisted before the flag went off cannot narrow a list that has no control for it.+ activeCreatedWindow: [+ (s) => [s.createdWindow, s.timeWindowAvailable],+ (createdWindow: InboxCreatedWindow | null, timeWindowAvailable: boolean): InboxCreatedWindow | null =>+ timeWindowAvailable ? createdWindow : null,],isRedesign: [(s) => [s.featureFlags],@@ -632,6 +744,8 @@ export const inboxFiltersLogic = kea<inboxFiltersLogicType>([setScope: toUrl,applyDefaultScope: toUrl,setSort: toUrl,+ setCreatedWindow: toUrl,+ applyDefaultCreatedWindow: toUrl,toggleSourceProduct: toUrl,toggleScout: toUrl,clearScoutFilter: toUrl,@@ -663,7 +777,7 @@ export const inboxFiltersLogic = kea<inboxFiltersLogicType>([// A shared link is authoritative: apply the params it carries and reset the rest to defaults.// Only dispatch when something actually changed — urlToAction also fires on plain navigation// (opening a report, switching tabs), and we don't want a redundant list refresh each time.- const parsed = parseFilterSearchParams(searchParams)+ const parsed = parseFilterSearchParams(searchParams, { modelSortAvailable: values.modelSortAvailable })const changed =values.scope !== parsed.scope ||!sameSet(values.sourceProductFilter, parsed.sourceProductFilter) ||@@ -672,7 +786,8 @@ export const inboxFiltersLogic = kea<inboxFiltersLogicType>([!sameSet(values.stateFilter, parsed.stateFilter) ||values.sortField !== parsed.sortField ||values.sortDirection !== parsed.sortDirection ||- values.searchQuery !== parsed.searchQuery+ values.searchQuery !== parsed.searchQuery ||+ values.createdWindow !== parsed.createdWindowif (changed) {actions.setFilters(parsed)}diff --git a/products/signals/frontend/inbox/logics/reportListLogic.ts b/products/signals/frontend/inbox/logics/reportListLogic.tsindex 2d70d24ab8fc..a7c539a7d368 100644--- a/products/signals/frontend/inbox/logics/reportListLogic.ts+++ b/products/signals/frontend/inbox/logics/reportListLogic.ts@@ -19,6 +19,7 @@ import {} from 'products/signals/frontend/generated/api'import type { SignalReportMetricSnapshotsApi } from 'products/signals/frontend/generated/api.schemas'+import { createdAfterForWindow } from '../filterOptions'import { captureInboxReportAction, type InboxReportActionSurface } from '../inboxAnalytics'import {INBOX_LEGACY_PRIMARY_REPORT_SECTION_KEY,@@ -38,7 +39,7 @@ import { isReportMetricsEnabled, mergeReportMetricSnapshots, reportNeedsMetricReimport { reportPullRequests, primaryReportPullRequest } from '../utils/reportPullRequests'import { inboxBulkActionsLogic } from './inboxBulkActionsLogic'import { buildSignalReportListOrdering, inboxFiltersLogic } from './inboxFiltersLogic'-import type { InboxFilterState, InboxSortDirection, InboxSortField } from './inboxFiltersLogic'+import type { InboxCreatedWindow, InboxFilterState, InboxSortDirection, InboxSortField } from './inboxFiltersLogic'import { prCiStatusLogic } from './prCiStatusLogic'const PAGE_SIZE = 50@@ -51,10 +52,28 @@ export type ReportSourceMeta = Pick<SignalReport, 'source_products' | 'scout_nam/** Fixed, section-defining server filter (e.g. `{ has_implementation_pr: 'true' }`). */export type ReportListParams = Record<string, string>+/** Display context of the query that produced a response, for telemetry. */+export interface ReportListRequestContext {+ scope: InboxScope+ hasActiveFilters: boolean+ sortField: InboxSortField+ sortDirection: InboxSortDirection+ createdWindow: InboxCreatedWindow | null+}+/** A list response stamped with the query params and display context that produced it (see the loader). */export type ReportListResponse = CountedPaginatedResponse<SignalReport> & {requestParams?: Record<string, unknown>- requestContext?: { scope: InboxScope; hasActiveFilters: boolean }+ requestContext?: ReportListRequestContext+}++/**+ * The list request for the API. `created_window` stays a preset key in `listApiParams`, so the+ * query key does not change every second, and turns into a `created_after` bound here, when the+ * request goes out.+ */+function listRequestParams({ created_window, ...params }: Record<string, any>): Record<string, any> {+ return { ...params, created_after: createdAfterForWindow(created_window ?? null) }}export interface ReportListLogicProps {@@ -109,14 +128,21 @@ function requestContextFromValues(values: {sourceProductFilter: string[]scoutFilter: string[]priorityFilter: SignalReportPriority[]-}): { scope: InboxScope; hasActiveFilters: boolean } {+ activeSortField: InboxSortField+ activeSortDirection: InboxSortDirection+ activeCreatedWindow: InboxCreatedWindow | null+}): ReportListRequestContext {return {scope: values.scope,hasActiveFilters:values.searchQuery.trim().length > 0 ||values.sourceProductFilter.length > 0 ||values.scoutFilter.length > 0 ||- values.priorityFilter.length > 0,+ values.priorityFilter.length > 0 ||+ values.activeCreatedWindow !== null,+ sortField: values.activeSortField,+ sortDirection: values.activeSortDirection,+ createdWindow: values.activeCreatedWindow,}}@@ -147,13 +173,14 @@ export function shouldDefaultToEntireProject(input: {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface reportListLogicValues {featureFlags: FeatureFlagsSet // featureFlagLogic+ activeCreatedWindow: InboxCreatedWindow | null // inboxFiltersLogic+ activeSortDirection: InboxSortDirection // inboxFiltersLogic+ activeSortField: InboxSortField // inboxFiltersLogichasUserChosenScope: boolean // inboxFiltersLogicpriorityFilter: SignalReportPriority[] // inboxFiltersLogicscope: InboxScope // inboxFiltersLogicscoutFilter: string[] // inboxFiltersLogicsearchQuery: string // inboxFiltersLogic- sortDirection: InboxSortDirection // inboxFiltersLogic- sortField: InboxSortField // inboxFiltersLogicsourceProductFilter: string[] // inboxFiltersLogiccurrentTeamId: number | null // teamLogicuser: UserType | null // userLogic@@ -163,10 +190,7 @@ export interface reportListLogicValues {isLoaded: booleanlistApiParams: anylivePrReportIds: string[]- loadedContext: {- hasActiveFilters: boolean- scope: InboxScope- } | null+ loadedContext: ReportListRequestContext | nullloadedQueryKey: string | nullpageLoadFailed: booleanprimarySectionKey: InboxReportSectionKey@@ -182,12 +206,18 @@ export interface reportListLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface reportListLogicActions {+ applyDefaultCreatedWindow: (createdWindow: InboxCreatedWindow) => {+ createdWindow: InboxCreatedWindow+ } // inboxFiltersLogicapplyDefaultScope: (scope: InboxScope) => {scope: InboxScope} // inboxFiltersLogicclearFilters: () => {value: true} // inboxFiltersLogic+ setCreatedWindow: (createdWindow: InboxCreatedWindow | null) => {+ createdWindow: InboxCreatedWindow | null+ } // inboxFiltersLogicsetFilters: (filters: InboxFilterState) => {filters: InboxFilterState} // inboxFiltersLogic@@ -325,12 +355,13 @@ export interface reportListLogicMeta {scopeReviewerUuid: (scope: InboxScope, user: UserType | null) => string | undefinedlistApiParams: (searchQuery: string,- sortField: InboxSortField,- sortDirection: InboxSortDirection,+ activeSortField: InboxSortField,+ activeSortDirection: InboxSortDirection,sourceProductFilter: string[],scoutFilter: string[],priorityFilter: SignalReportPriority[],scopeReviewerUuid: string | undefined,+ activeCreatedWindow: InboxCreatedWindow | null,arg: any) => anyreports: (@@ -343,10 +374,7 @@ export interface reportListLogicMeta {livePrReportIds: (reports: SignalReport[]) => string[]totalCount: (reportsResponse: ReportListResponse | null) => number | nullloadedQueryKey: (reportsResponse: ReportListResponse | null) => string | null- loadedContext: (reportsResponse: ReportListResponse | null) => {- hasActiveFilters: boolean- scope: InboxScope- } | null+ loadedContext: (reportsResponse: ReportListResponse | null) => ReportListRequestContext | null}}@@ -380,11 +408,12 @@ export const reportListLogic = kea<reportListLogicType>(['scope','hasUserChosenScope','searchQuery',- 'sortField',- 'sortDirection',+ 'activeSortField',+ 'activeSortDirection','sourceProductFilter','scoutFilter','priorityFilter',+ 'activeCreatedWindow',],userLogic,['user'],@@ -406,6 +435,8 @@ export const reportListLogic = kea<reportListLogicType>(['applyDefaultScope','setFilters','clearFilters',+ 'setCreatedWindow',+ 'applyDefaultCreatedWindow',],prCiStatusLogic,['trackReports'],@@ -438,8 +469,9 @@ export const reportListLogic = kea<reportListLogicType>([null as number | null,{loadCount: async () => {+ // nosemgrep: prefer-codegen-api-namespaced-signals -- the Inbox renders the handwritten SignalReport. The generated report type is wider (string status and priority, read-only arrays), so the list calls move to generated types together with the Inbox.const response = await api.signalReports.list({- ...values.listApiParams,+ ...listRequestParams(values.listApiParams),limit: 1,count_only: 'true',})@@ -456,7 +488,12 @@ export const reportListLogic = kea<reportListLogicType>([loadReports: async (): Promise<ReportListResponse> => {const params = values.listApiParamsconst requestContext = requestContextFromValues(values)- const response = await api.signalReports.list({ ...params, offset: 0, limit: PAGE_SIZE })+ // nosemgrep: prefer-codegen-api-namespaced-signals -- the Inbox renders the handwritten SignalReport. The generated report type is wider (string status and priority, read-only arrays), so the list calls move to generated types together with the Inbox.+ const response = await api.signalReports.list({+ ...listRequestParams(params),+ offset: 0,+ limit: PAGE_SIZE,+ })return { ...response, requestParams: params, requestContext }},loadMoreReports: async (): Promise<ReportListResponse> => {@@ -467,8 +504,9 @@ export const reportListLogic = kea<reportListLogicType>([// those removals, so filter them out or a removed report comes back when the page lands.const removedWhilePending = new Set<string>()cache.removedWhilePageLoads = removedWhilePending+ // nosemgrep: prefer-codegen-api-namespaced-signals -- the Inbox renders the handwritten SignalReport. The generated report type is wider (string status and priority, read-only arrays), so the list calls move to generated types together with the Inbox.const response = await api.signalReports.list({- ...params,+ ...listRequestParams(params),offset: current.length,limit: PAGE_SIZE,})@@ -561,12 +599,13 @@ export const reportListLogic = kea<reportListLogicType>([listApiParams: [(s) => [s.searchQuery,- s.sortField,- s.sortDirection,+ s.activeSortField,+ s.activeSortDirection,s.sourceProductFilter,s.scoutFilter,s.priorityFilter,s.scopeReviewerUuid,+ s.activeCreatedWindow,(_, p) => p.listParams,],(@@ -577,6 +616,7 @@ export const reportListLogic = kea<reportListLogicType>([scoutFilter: string[],priorityFilter: import('../types').SignalReportPriority[],suggestedReviewer: string | undefined,+ activeCreatedWindow: InboxCreatedWindow | null,listParams) => {return {@@ -587,6 +627,7 @@ export const reportListLogic = kea<reportListLogicType>([scout: scoutFilter.length > 0 ? scoutFilter.join(',') : undefined,priority: priorityFilter.length > 0 ? priorityFilter.join(',') : undefined,suggested_reviewers: suggestedReviewer,+ created_window: activeCreatedWindow ?? undefined,// Rows render from Postgres alone; `loadReportSourceMeta` fills the source line after.include_source_metadata: 'false',}@@ -657,7 +698,7 @@ export const reportListLogic = kea<reportListLogicType>([// user switched to after the request went out.loadedContext: [(s) => [s.reportsResponse],- (reportsResponse: ReportListResponse | null): { scope: InboxScope; hasActiveFilters: boolean } | null =>+ (reportsResponse: ReportListResponse | null): ReportListRequestContext | null =>reportsResponse?.requestContext ?? null,],}),@@ -770,6 +811,8 @@ export const reportListLogic = kea<reportListLogicType>([actions.refresh()},setSort: () => actions.refresh(),+ setCreatedWindow: () => actions.refresh(),+ applyDefaultCreatedWindow: () => actions.refresh(),toggleSourceProduct: () => actions.refresh(),toggleScout: () => actions.refresh(),togglePriority: () => actions.refresh(),diff --git a/products/signals/frontend/inbox/types.ts b/products/signals/frontend/inbox/types.tsindex 25e372400c5e..26975e116431 100644--- a/products/signals/frontend/inbox/types.ts+++ b/products/signals/frontend/inbox/types.ts@@ -3,6 +3,7 @@ import type { UserBasicType } from '~/types'import {type ReportChartApi,type ReportMetricApi,+ type ReportRankingApi,type SignalReportPullRequestApi,type SignalReportAssigneeApi,type SignalReportAssignmentPrStateEnumApi,@@ -137,6 +138,8 @@ export interface SignalReport {billing_exempt_reason?: string | null/** Backend-owned refund eligibility: why a refund would be rejected right now, null when it would be accepted. */refund_ineligibility_reason?: string | null+ /** The served ranking model's score. Staff only: null for other users and for unscored reports. */+ ranking?: ReportRankingApi | null}export enum SignalReportStatus {diff --git a/products/signals/frontend/inbox/utils/reportOrdering.ts b/products/signals/frontend/inbox/utils/reportOrdering.tsindex 365ef764c56f..d1fd12ca3923 100644--- a/products/signals/frontend/inbox/utils/reportOrdering.ts+++ b/products/signals/frontend/inbox/utils/reportOrdering.ts@@ -1,4 +1,5 @@-import type { InboxSortDirection, InboxSortField } from '../logics/inboxFiltersLogic'+import { isRankingSortField, RANKING_SORT_HEADS } from '../filterOptions'+import type { InboxRankingSortField, InboxSortDirection, InboxSortField } from '../logics/inboxFiltersLogic'import { SignalReport, SignalReportStatus } from '../types'/**@@ -46,6 +47,20 @@ function timestampKey(value: string): string {return value.includes('.') ? value : value.replace(/(Z|[+-]\d\d:?\d\d)$/, '.000000$1')}+/** The served probability a model sort orders by, or null when the report has no score for that head. */+export function rankingSortScore(report: SignalReport, field: InboxRankingSortField): number | null {+ const score = report.ranking?.scores[RANKING_SORT_HEADS[field].head]+ return typeof score === 'number' ? score : null+}++// The server puts unscored reports after every scored report, in both directions.+function compareRankingScores(a: number | null, b: number | null, dir: number): number {+ if (a === null || b === null) {+ return a === b ? 0 : a === null ? 1 : -1+ }+ return dir * (a - b)+}+/** Comparator over reports for the given sort selection. Stable input order breaks remaining ties. */export function compareSignalReports(field: InboxSortField,@@ -53,12 +68,19 @@ export function compareSignalReports(): (a: SignalReport, b: SignalReport) => number {const dir = direction === 'desc' ? -1 : 1return (a, b) => {- const primary =- field === 'priority'- ? compareStrings(priorityKey(a), priorityKey(b))- : compareStrings(timestampKey(a[field]), timestampKey(b[field]))- if (primary !== 0) {- return dir * primary+ if (isRankingSortField(field)) {+ const ranking = compareRankingScores(rankingSortScore(a, field), rankingSortScore(b, field), dir)+ if (ranking !== 0) {+ return ranking+ }+ } else {+ const primary =+ field === 'priority'+ ? compareStrings(priorityKey(a), priorityKey(b))+ : compareStrings(timestampKey(a[field]), timestampKey(b[field]))+ if (primary !== 0) {+ return dir * primary+ }}const rank = statusRank(a) - statusRank(b)if (rank !== 0) {diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex cb69a03ba731..8cf0af7eba18 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -120906,6 +120906,10 @@ export namespace Schemas {* Return the filtered total with an empty results page. Skips report ordering, serialization, and decorative metadata lookups. Defaults to false.*/count_only?: boolean;+ /**+ * ISO 8601 datetime. Keeps reports created at or after this time.+ */+ created_after?: string;/*** Filter reports by whether an implementation pull request is attached. 'true' keeps only reports with a PR; 'false' keeps only those without. Pair with count_only=true to return only the filtered total.*/@@ -120927,7 +120931,7 @@ export namespace Schemas {*/offset?: number;/**- * Comma-separated ordering clauses. Each clause is a field name optionally prefixed with '-' for descending. Allowed fields: status, is_suggested_reviewer, signal_count, total_weight, priority, created_at, updated_at, id. Defaults to '-is_suggested_reviewer,status,-updated_at'.+ * Comma-separated ordering clauses. Each clause is a field name optionally prefixed with '-' for descending. Allowed fields: status, is_suggested_reviewer, signal_count, total_weight, priority, created_at, updated_at, id, ranking_pr_merged, ranking_pr_created, ranking_action, ranking_open. Defaults to '-is_suggested_reviewer,status,-updated_at'. The ranking_* fields sort by the served ranking model's probability for that outcome head, with unscored reports last in either direction. They are staff only: other users get a 400.*/ordering?: string;/**diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.tsindex dcce31f13dcc..5dbe76b8e86c 100644--- a/services/mcp/src/generated/signals/api.ts+++ b/services/mcp/src/generated/signals/api.ts@@ -48,6 +48,10 @@ export const SignalsReportsListQueryParams = () => zod.object({.describe('Return the filtered total with an empty results page. Skips report ordering, serialization, and decorative metadata lookups. Defaults to false.'),+ created_after: zod.iso+ .datetime({ offset: true })+ .optional()+ .describe('ISO 8601 datetime. Keeps reports created at or after this time.'),has_implementation_pr: zod.boolean().optional()@@ -72,7 +76,7 @@ export const SignalsReportsListQueryParams = () => zod.object({.string().optional().describe(- "Comma-separated ordering clauses. Each clause is a field name optionally prefixed with '-' for descending. Allowed fields: status, is_suggested_reviewer, signal_count, total_weight, priority, created_at, updated_at, id. Defaults to '-is_suggested_reviewer,status,-updated_at'."+ "Comma-separated ordering clauses. Each clause is a field name optionally prefixed with '-' for descending. Allowed fields: status, is_suggested_reviewer, signal_count, total_weight, priority, created_at, updated_at, id, ranking_pr_merged, ranking_pr_created, ranking_action, ranking_open. Defaults to '-is_suggested_reviewer,status,-updated_at'. The ranking_\* fields sort by the served ranking model's probability for that outcome head, with unscored reports last in either direction. They are staff only: other users get a 400."),priority: zod.string()diff --git a/services/mcp/src/tools/generated/signals.ts b/services/mcp/src/tools/generated/signals.tsindex 251600ad4abe..2c702eab63b6 100644--- a/services/mcp/src/tools/generated/signals.ts+++ b/services/mcp/src/tools/generated/signals.ts@@ -352,6 +352,7 @@ const inboxReportsList = (): ToolBase<assignee: params.assignee,channel_id: params.channel_id,count_only: params.count_only,+ created_after: params.created_after,has_implementation_pr: params.has_implementation_pr,include_all_statuses: params.include_all_statuses,include_source_metadata: params.include_source_metadata,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-reports-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-reports-list.jsonindex 0ba57ecd4e44..9a77759e6c8c 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-reports-list.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-reports-list.json@@ -23,6 +23,12 @@"description": "Return the filtered total with an empty results page. Skips report ordering, serialization, and decorative metadata lookups. Defaults to false.","type": "boolean"},+ "created_after": {+ "description": "ISO 8601 datetime. Keeps reports created at or after this time.",+ "format": "date-time",+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$",+ "type": "string"+ },"has_implementation_pr": {"description": "Filter reports by whether an implementation pull request is attached. 'true' keeps only reports with a PR; 'false' keeps only those without. Pair with count_only=true to return only the filtered total.","type": "boolean"@@ -45,7 +51,7 @@"type": "number"},"ordering": {- "description": "Comma-separated ordering clauses. Each clause is a field name optionally prefixed with '-' for descending. Allowed fields: status, is_suggested_reviewer, signal_count, total_weight, priority, created_at, updated_at, id. Defaults to '-is_suggested_reviewer,status,-updated_at'.",+ "description": "Comma-separated ordering clauses. Each clause is a field name optionally prefixed with '-' for descending. Allowed fields: status, is_suggested_reviewer, signal_count, total_weight, priority, created_at, updated_at, id, ranking_pr_merged, ranking_pr_created, ranking_action, ranking_open. Defaults to '-is_suggested_reviewer,status,-updated_at'. The ranking_* fields sort by the served ranking model's probability for that outcome head, with unscored reports last in either direction. They are staff only: other users get a 400.","type": "string"},"priority": {