: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): one flat inbox reports list with state and scope filters (#91669)
Chris Volzerad025549c47c
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 7ca8018c3992..5d62afb8d0e4 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6933,9 +6933,9 @@ snapshots:scenes-app-inbox-cards--pull-request-cards--light:hash: v1.k794b7964.96341b9eb9faf150c5136df9e3037258ab04e1bbca0db68132ad0b6eef208a3f.5x1VdsQAsZIQYuUhXHfsYknb6esQvidkGn1A8c8rasMscenes-app-inbox-cards--report-card-states--dark:- hash: v1.k794b7964.ba16a83dbf182e4d040a5b2ef939356eebf61d57d8badf9c2ee7b2e854bbf19e.g72SQhrMazGwfmcj6TgTgKmvlZGPwYmdV5ptNMQTbCo+ hash: v1.k794b7964.33b10f41bb9d6b0c0df486790da1941c2bda06737db7b4bc5673e5db4f3f720c.3WZPIG_1hITQ6eq4axwfpT-fORwsKSYegfDJgqOOdU4scenes-app-inbox-cards--report-card-states--light:- hash: v1.k794b7964.24d2afec43992f4bebdec20954ceac9cc83db082793b82555277e6a303afcf06.8S1CerSeXjnYQ7mcP83n1J7riiHc6Ls9WPCKKElLIlU+ hash: v1.k794b7964.f64c9e0b53fe1c3c522d2f809948c5f06abdedc6dd19c75c20e0417967a325da.jVmHII9BuoIEVBu4R4ofLtGZH_R0_v96gUuRd-pjo_Uscenes-app-inbox-cards--report-cards--dark:hash: v1.k794b7964.4f6a69243d31ecf3af3bd8e9a2910b86d739144f1a084124d90a5ce4329ae3b4.8-FcdTNkh7g8C59SeYucGlaSmzu5lZYBF4nqUXKcmPgscenes-app-inbox-cards--report-cards--light:@@ -7021,25 +7021,25 @@ snapshots:scenes-app-inbox-pullrequestdiffview--truncated--light:hash: v1.k794b7964.58a507666519d2ad2f2a5247605b2c903180639eae9e43580992de250bc8f258._lKwsnOWccjuN6S_pd8IgOfKLzqnIvVqmTh1uETW-TYscenes-app-inbox-scene--empty--dark:- hash: v1.k794b7964.18f637086799dbed78b0b1f7b4e515e28ef6384c3d1f73fae36a63268689b34d.nYA0vYbbnNgEVD_KRwpA3pO42DrrVonzElXVtiX3KQg+ hash: v1.k794b7964.7d08781760f326f7746ad15883a7ad1a12af173a118c112947ec8ad2637cb1e1.9lq59SDcw12Zz9wZmdfDUnV8V-8vVzWL4NZ0QbTOMgUscenes-app-inbox-scene--empty--light:- hash: v1.k794b7964.9be5803d6d4ef01e3ac3427ce20e2a27944a5470750c7e1db6107f74c1275337.rH7qOSAE5TAFdExQa3wmCEz6BhUPUsy848kbvaGzzpk+ hash: v1.k794b7964.70d46b83d374799f0fa32a86442a324f89b4dc5891114b47fd18b6f4beeb5a72.bY2Vjl09QImFY6oHwS8QTTZzb_zMPQJcg4eZkZLeCDsscenes-app-inbox-scene--empty-control--dark:- hash: v1.k794b7964.03efcbc7b7ab0a990cb5975ce89a45561afa6f1800ed5d54ab50ba9d102c18ae.kQLk9Tk6zDY6eMBe0BbT6WxqnSbGFT8KKfVg-mMqSmU+ hash: v1.k794b7964.c3b310e693423d075fbc89cdf980da883e83c2dcb875de9e81fe2f58f65eb69a.bWCTpI3O_lPdfX3K-LYQvQuAxAYonfQER2mBaUh5eEMscenes-app-inbox-scene--empty-control--light:- hash: v1.k794b7964.e260473c9361bf1993b204da699cc818274a48032e8b5a5ebe54f8bab82bd392.nAnvZ0JDprivxCc103R9zV7AuNS3bexcp92-JPMAGnw+ hash: v1.k794b7964.40a8eaced770971fbe50173245db2b8f173948320a09b1f0a138ca90819e0c1a.FTwYK7wfCfCxR-YFKOLhK5ejxXe4qYDEjxWf2tG3vQoscenes-app-inbox-scene--empty-with-many-scouts--dark:- hash: v1.k794b7964.7b37c09832bd339a3f70ad6bef4e9224903ef88d2d34daea962c6162d4323b70.n8dkuQm69NZJ-8vl4mjQOgB4ESE1OtmITlbCXMlvSX8+ hash: v1.k794b7964.737eadc375ed0122478682812983b6139a399fe35c0b61b8212b5fdda1e15ebd.tcmc5t1Jpg2JjZ5l4ASoJTE8_U5E6HrOWsGghi-uoGIscenes-app-inbox-scene--empty-with-many-scouts--light:- hash: v1.k794b7964.0c84994341ed9cd1f4767d6e6c54ad028f49e60ebc944885276d83fa01856c31.3WAZPr2nXoGAZRRxPHw9RDbS4jrCWJNdp4fsyZOjFkk+ hash: v1.k794b7964.e254ce785e328a8e47e53362026f920ddf77a2b7dd6402f6ad56c02e3590af4a.CiyEQnzqVrx-u3Q-nCE5ludmZMsIMXGJOa7TTxycB0Escenes-app-inbox-scene--inbox--dark:hash: v1.k794b7964.e1e4ab0d21ba58926ab2d57e366734264122b146701a84fe3f442012ec64fc19.6sbEcCnUZmsj3KMtQMzsKHuyPxgs2UIKKF6xN7gufSAscenes-app-inbox-scene--inbox--light:hash: v1.k794b7964.ac152ef65c5c6fe25d9b985a44f41279a017eff249d66920bcd77bbc17f78b64.B22XE-debF5iSr7REBQIZ9TrQN2y0pgYWX8tIS-_Vv4scenes-app-inbox-scene--installing-self-driving--dark:- hash: v1.k794b7964.269746cc24d0f9d069b7fc19d8426ea0614033f0a548273c5437a047a22cb3bd.hK2SPJ4ZCKtMKqdEOhReNzFC5NqXdUoaSuBgYrHJq00+ hash: v1.k794b7964.9b4caff813eafd13634c23944b6864b2e5e780612b7c7582853b1641fd6069d6.BpcSU8wtvBqJ6wuJ1eDHKkzYRHbGFpA2FkvwTu64kkYscenes-app-inbox-scene--installing-self-driving--light:- hash: v1.k794b7964.41a47fbbfb7f9e86e28b25e0fec8fb1dea400e7808b56c7c2c5f7a6f963553eb.8A4Rn9qwBlPvKpciU4ZTVt01K2UsWFSKdolw-plZfKU+ hash: v1.k794b7964.453f01ffd0289dd1b08046837544243ec7ec9bda56c3f4abeec7c768fa18e821.UtCIrnnSZtamR7C4EyDiY3QNBoJq33ekC2bqcVXPKQsscenes-app-inbox-scene--legacy--dark:hash: v1.k794b7964.82fb69396eaab9ceb5a1223541105145370974e4cbb950bfe12ff201770b628b.0CZuUPcENgOU_VVhM4Ooj3YUlrXnMNAWbFCT0JGQzWUscenes-app-inbox-scene--legacy--light:@@ -7061,9 +7061,9 @@ snapshots:scenes-app-inbox-scene--self-driving-onboarding--light:hash: v1.k794b7964.5268ad52b39cdc5bb1d699e6a1a839a552ce397134d6773714e1f5a2d95994b6.hgkYOJDE9ZNZ0mMtcj9cpcDCtmas-opelntO_tyQ9Igscenes-app-inbox-scene--self-driving-paused--dark:- hash: v1.k794b7964.60911ae280a03886530975a4cd39b2ddaf6d1a7103a313a1f800d7a42cddee35.Y8Sb9v0E_DYvJ89JRyPxQejbUpmHipZ7JuvM1WFRyMA+ hash: v1.k794b7964.b5432aa0409fb72bd8df3c1c914d7303bfa4b13bcad3ea72474526986bc53d1f.ifHdPrnNKpfuPKc_en16o1gOogrh3vh7vjM8D2eBZw0scenes-app-inbox-scene--self-driving-paused--light:- hash: v1.k794b7964.033fd2c05dcdb683b4147896428653092c1952d69439ac35481de90b8d926ae6.TNnPVe7tq65qZEe-umw43NvxSH0pxhgiiFJKwo5eXKo+ hash: v1.k794b7964.68c5a0b4b3a71f9d57ebd22d85c5aedfc6704872ee036cf00c7ba2cf83e4f0c8.k5ktgrWKHvJI9sH0wPbcQ4YI64a33tQ-5oSG_YpCjXwscenes-app-inbox-scene--self-driving-verdict-pending--dark:hash: v1.k794b7964.570e5dddd645996b94ff94b2c563b32ced3793db3ab5ccf360d16126af3b9a0b.WC_VEZ1N_iX-o4r11w15QWfD8Nzo1gFerTznKiaIX84scenes-app-inbox-scene--self-driving-verdict-pending--light:@@ -7205,21 +7205,21 @@ snapshots:scenes-app-inbox-tabs--pull-requests-legacy--light:hash: v1.k794b7964.d66d0f73814191c857a64891ddd73dbbca609b40f71b80b5a97b95b1d0ed5d0d.coTm8czKJGGrvOoP28HGqgyV0I1HTpvp14uWHt7b4dQscenes-app-inbox-tabs--reports--dark:- hash: v1.k794b7964.c85f18207a5cd24dfb6f087a18ecd2156c1a9f5e76ad47cc041b266caab06587.xELuHAi4lH3Xs2a2bObdfnLztO2C6YKN2lWnOsKuaYo+ hash: v1.k794b7964.fe27a895558915d24de4ef9f9511479ebcd0782da864a5d1b85f81b5263327a3.wCHia_XS0ZgsPveDc9FPERSvKwbu8uzGer6NY7jUvG8scenes-app-inbox-tabs--reports--light:- hash: v1.k794b7964.fa80701fb9b9e6653ef8c7a646e9f710d66863cfd7fab678de5cbe7d31127a74.HmDKcwJDlzTlvc1u8vdBQLgB-WVsOq3ogCMrgFlgZEo- scenes-app-inbox-tabs--reports-all-sections-expanded--dark:- hash: v1.k794b7964.31989b8f37efb2b2a553f95cee62f7e5333651b9f6d2ac97f2098cfa2d6f620e.k_0TpkPYmZKMUu3GYQynFHVpZW5S165b0gGIlblCdZI- scenes-app-inbox-tabs--reports-all-sections-expanded--light:- hash: v1.k794b7964.02a6ab0a9e2e9a876c4ed6f461ed58bb6f68c2eef94f9b099c582452752be7e8.ESbmLMcQQZUfAE9lxzUw4B5LVKsY6d668Y9XRlBlcIw+ hash: v1.k794b7964.3de600060cd59ed20fe68fe175911b3ca30a42e434c72258b6e45054d3777e6b.RJUlFpkeZ-ZdCFpGYrESLRPVmSAfz8PBUJTRJ50nhVwscenes-app-inbox-tabs--reports-empty--dark:- hash: v1.k794b7964.fadcb6a49ae519ed7432563af517599477371bc1e9823b09c7a1cc351925b249.FHSWD8X0Bg6UfdgpmdkK_3y1cIiWzBwfN5WCvTWLV2w+ hash: v1.k794b7964.a84b301c5e7b2f3b614ae70fd79cb33521d4702790bdfe4a4dcad0816a78152e.y29PsyMQdbg-pSBHIijqi2DdHAXSdJTGVyGKvsnPn1Escenes-app-inbox-tabs--reports-empty--light:- hash: v1.k794b7964.3a6b3393d02f9fbc789213e7ff4ca0ab90a0cb31962995cc42ce547dff9719fe.Tg74pzAgyn6wyvXNoPcUZuobn29C3aOLd5LoX0aFbCQ+ hash: v1.k794b7964.1194d41f9543372cda988c41560c2f79572ae1e4e029ede557415a44d7ab991e.9ISKBHELesQSttTAc1KUzKuISboUxudlJjjm8cDrjZ4scenes-app-inbox-tabs--reports-legacy--dark:hash: v1.k794b7964.6bffd9df9241aef3533411aba5c41ba3b0d0ad7bd5701e5f8a0da414e0710700.-BcMQAuZIxfrd2EioB1VGkALBdOQqgN9Y1g3CmfC7Q0scenes-app-inbox-tabs--reports-legacy--light:hash: v1.k794b7964.7864bdacc54e80bd704a403fb813da48779160b95ad014df7bbae8a84a5d24a3.7J1YPQyUSF6iat2oGdHpGn1E3Ml0eTRtyb64GwDL334+ scenes-app-inbox-tabs--reports-state-filtered--dark:+ hash: v1.k794b7964.07fcb6553c47520c1766a69337feadface4958b28773600ba13c08dd59832b8b.4mws9NjCYtzE7-PnmMW5eqGpEdk7tXixAXvASeFveLE+ scenes-app-inbox-tabs--reports-state-filtered--light:+ hash: v1.k794b7964.31a1d83607d003d30e3aa348ac4323b03fcc22ebcb1ba1a1d1617970596d52db.Nw_djmZopFPyc_6tj_hyUqVh_oo5Ytz6kmSluwo8S0Iscenes-app-inbox-tabs--runs--dark:hash: v1.k794b7964.4ece3bdc6be5207a77eafc6d9005ce3a065539767d7a4da5f3f2f5f913bb3567.Wu4dnjXImAjEXPa2f8AdBAeJIwpnA-ak02ZeHI87kBoscenes-app-inbox-tabs--runs--light:diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 8431b4c557b9..7c02d81822f7 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -5190,6 +5190,8 @@ const api = {scout?: string/** Scout skill_name prefix — matches every scout in the family. */scout_prefix?: string+ /** true returns only the filtered total: `results` is empty and no rows are serialized. */+ count_only?: 'true' | 'false'}): Promise<CountedPaginatedResponse<SignalReport>> {return await new ApiRequest().signalReports().withQueryString(params).get()},diff --git a/products/signals/frontend/inbox/components/InboxReportSection.test.tsx b/products/signals/frontend/inbox/components/InboxReportSection.test.tsxdeleted file mode 100644index 2b37a2e47979..000000000000--- a/products/signals/frontend/inbox/components/InboxReportSection.test.tsx+++ /dev/null@@ -1,140 +0,0 @@-/* oxlint-disable react-hooks/rules-of-hooks -- useMocks is a test helper, not a React hook */-import '@testing-library/jest-dom'--import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'--import { useMocks } from '~/mocks/jest'-import { initKeaTests } from '~/test/init'--import { inboxReportSectionsLogic } from '../logics/inboxReportSectionsLogic'-import { SignalReportStatus } from '../types'-import { InboxReportSection } from './InboxReportSection'--// The card and the impression log are unrelated to when rows are fetched, and both pull in the-// whole inbox scene.-jest.mock('./cards/ReportCard', () => ({- ReportCard: ({ report }: { report: { id: string; title: string } }) => <div>{report.title}</div>,-}))-jest.mock('./useReportImpressions', () => ({ useReportImpressions: () => undefined }))--describe('InboxReportSection', () => {- let pageRequests: number-- beforeEach(() => {- // Section expand/collapse persists to localStorage, which initKeaTests does not clear — wipe- // it so each test starts from the default open/closed state rather than a prior test's toggle.- localStorage.clear()- pageRequests = 0- useMocks({- get: {- '/api/projects/:team_id/signals/reports/available_reviewers': {},- '/api/projects/:team_id/signals/reports/': ({ request }) => {- // The header count is a separate count-only request, and a collapsed section is- // still entitled to make it.- if (new URL(request.url).searchParams.get('limit') !== '1') {- pageRequests += 1- }- return [- 200,- {- count: 1,- next: null,- previous: null,- results: [- {- id: 'r1',- title: 'A report',- summary: 'summary',- status: SignalReportStatus.READY,- total_weight: 0,- signal_count: 1,- relevant_user_count: null,- artefact_count: 0,- is_suggested_reviewer: false,- created_at: '2026-06-11T10:00:00Z',- updated_at: '2026-06-11T10:00:00Z',- },- ],- },- ]- },- },- })- initKeaTests()- })-- afterEach(cleanup)-- // Four sections render at once. If a collapsed one loaded its rows anyway, every visit would- // pull a full page per section for content nobody asked to see.- it('loads rows only once the section is expanded', async () => {- // Resolved starts collapsed.- render(<InboxReportSection sectionKey="resolved" />)-- await screen.findByText('Resolved')- expect(screen.queryByText('A report')).not.toBeInTheDocument()- expect(pageRequests).toBe(0)-- inboxReportSectionsLogic.findMounted()?.actions.toggleSection('resolved')-- await screen.findByText('A report')- await waitFor(() => expect(pageRequests).toBe(1))- })-- // A failed first fetch leaves `reportsResponse` null, so the section used to skeleton forever with- // no way to recover. It must show a retry instead.- it('shows a retry instead of a stuck skeleton when the first fetch fails', async () => {- let failPage = true- useMocks({- get: {- '/api/projects/:team_id/signals/reports/available_reviewers': {},- '/api/projects/:team_id/signals/reports/': ({ request }) => {- // The header count is a separate request that keeps working.- if (new URL(request.url).searchParams.get('limit') === '1') {- return [200, { count: 1, next: null, previous: null, results: [] }]- }- if (failPage) {- return [500, {}]- }- return [- 200,- {- count: 1,- next: null,- previous: null,- results: [- {- id: 'r1',- title: 'A report',- summary: 'summary',- status: SignalReportStatus.READY,- total_weight: 0,- signal_count: 1,- relevant_user_count: null,- artefact_count: 0,- is_suggested_reviewer: false,- created_at: '2026-06-11T10:00:00Z',- updated_at: '2026-06-11T10:00:00Z',- },- ],- },- ]- },- },- })-- render(<InboxReportSection sectionKey="resolved" />)- await screen.findByText('Resolved')- inboxReportSectionsLogic.findMounted()?.actions.toggleSection('resolved')-- // The failed load surfaces a retry, not a permanent skeleton.- await screen.findByText("Couldn't load these reports.")-- // Retrying now succeeds and the row lands, clearing the error.- failPage = false- fireEvent.click(screen.getByText('Retry'))-- await screen.findByText('A report')- expect(screen.queryByText("Couldn't load these reports.")).not.toBeInTheDocument()- })-})diff --git a/products/signals/frontend/inbox/components/InboxReportSection.tsx b/products/signals/frontend/inbox/components/InboxReportSection.tsxdeleted file mode 100644index 6e9922373643..000000000000--- a/products/signals/frontend/inbox/components/InboxReportSection.tsx+++ /dev/null@@ -1,157 +0,0 @@-import { BindLogic, useActions, useValues } from 'kea'-import { JSX, useEffect } from 'react'--import { IconChevronDown } from '@posthog/icons'-import { LemonButton, LemonSkeleton, LemonTag } from '@posthog/lemon-ui'--import { cn } from 'lib/utils/css-classes'--import { inboxReportSectionsLogic } from '../logics/inboxReportSectionsLogic'-import { INBOX_REPORT_SECTION_LIST_PARAMS, reportListLogic } from '../logics/reportListLogic'-import {- INBOX_REPORT_SECTION_DESCRIPTION,- INBOX_REPORT_SECTION_LABEL,- INBOX_REPORT_SECTION_TAG,- InboxReportSectionKey,-} from '../types'-import { CardSkeleton } from './cards/CardSkeleton'-import { ReportCard } from './cards/ReportCard'-import { useReportImpressions } from './useReportImpressions'--/** Copy shown in place of the rows when a section matches nothing. */-const EMPTY_SECTION_COPY: Record<InboxReportSectionKey, string> = {- 'needs-decision': 'No reports are waiting for a pull request.',- monitoring: 'No pull requests open yet. Start one from a report above.',- resolved: 'Nothing resolved yet.',- dismissed: 'Nothing dismissed yet.',- 'not-actionable': 'Nothing has been judged not actionable.',-}--/**- * One section of the Reports list: a collapsible run of report cards over its own filtered request.- * The header carries the section's count whether or not it is expanded, so a collapsed section still- * says how much is behind it; the rows themselves only load once it opens.- */-export function InboxReportSection({ sectionKey }: { sectionKey: InboxReportSectionKey }): JSX.Element {- return (- <BindLogic- logic={reportListLogic}- props={{ sectionKey, listParams: INBOX_REPORT_SECTION_LIST_PARAMS[sectionKey] }}- >- <section className="flex flex-col gap-2">- <SectionHeader sectionKey={sectionKey} />- <SectionBody sectionKey={sectionKey} />- </section>- </BindLogic>- )-}--function SectionHeader({ sectionKey }: { sectionKey: InboxReportSectionKey }): JSX.Element {- const { count, countLoading } = useValues(reportListLogic)- const { openSections } = useValues(inboxReportSectionsLogic)- const { toggleSection } = useActions(inboxReportSectionsLogic)- const isOpen = openSections[sectionKey]- const tag = INBOX_REPORT_SECTION_TAG[sectionKey]-- return (- <button- type="button"- className="flex w-full cursor-pointer items-center gap-2 rounded px-0.5 py-1 text-left"- onClick={() => toggleSection(sectionKey)}- aria-expanded={isOpen}- title={INBOX_REPORT_SECTION_DESCRIPTION[sectionKey]}- data-attr={`inbox-report-section-${sectionKey}`}- >- <span className="flex items-center gap-1 font-mono text-[11px] font-semibold uppercase tracking-widest text-secondary">- {INBOX_REPORT_SECTION_LABEL[sectionKey]}- {/* Skeleton only while the request is genuinely in flight; on failure `count` stays- null, so fall back to the number (0) rather than a permanent skeleton. */}- {count === null && countLoading ? (- <LemonSkeleton className="h-3 w-4 rounded" />- ) : (- <span className="tabular-nums">({count ?? 0})</span>- )}- </span>- {tag && (- <LemonTag type="completion" size="small">- {tag}- </LemonTag>- )}- <div className="h-px flex-1 bg-border-primary" />- <IconChevronDown className={cn('text-tertiary transition-transform', isOpen && 'rotate-180')} />- </button>- )-}--function SectionBody({ sectionKey }: { sectionKey: InboxReportSectionKey }): JSX.Element | null {- const { visibleReports, hiddenReportCount, count, isLoaded, reportsLoadFailed, reportsResponseLoading } =- useValues(reportListLogic)- const { ensureLoaded, showMore, restoreReport } = useActions(reportListLogic)- const { openSections } = useValues(inboxReportSectionsLogic)- const isOpen = openSections[sectionKey]-- useReportImpressions(sectionKey, isOpen)-- // Rows are fetched on first expand, not on mount — a collapsed section costs one count request.- useEffect(() => {- if (isOpen) {- ensureLoaded()- }- }, [isOpen, ensureLoaded])-- if (!isOpen) {- return null- }- // The first fetch failed: kea loaders keep the response null, so `isLoaded` never flips. Show a- // retry instead of a skeleton that would otherwise spin forever with no way to recover.- if (!isLoaded && reportsLoadFailed) {- return (- <div className="flex flex-col items-start gap-2 px-1 py-2">- <p className="m-0 text-sm text-tertiary">Couldn't load these reports.</p>- <LemonButton- size="small"- type="secondary"- onClick={() => ensureLoaded()}- data-attr={`inbox-report-section-retry-${sectionKey}`}- >- Retry- </LemonButton>- </div>- )- }- // Loading, then empty, then content: `reports` is empty during the first fetch too, and a- // section that is about to show ten rows must not flash "nothing here" on the way.- if (!isLoaded) {- return <CardSkeleton count={Math.min(count || 3, 5)} variant="cards" dashed={sectionKey !== 'monitoring'} />- }- if (visibleReports.length === 0) {- return <p className="px-1 py-2 text-sm text-tertiary">{EMPTY_SECTION_COPY[sectionKey]}</p>- }-- return (- <div className="flex flex-col gap-1.5">- {visibleReports.map((report) => (- <ReportCard- key={report.id}- report={report}- sectionKey={sectionKey}- onRestore={() => restoreReport(report.id)}- />- ))}- {hiddenReportCount > 0 && (- <div className="flex justify-center pt-1">- <LemonButton- size="small"- type="tertiary"- onClick={showMore}- loading={reportsResponseLoading}- disabledReason={reportsResponseLoading ? 'Loading more reports' : undefined}- data-attr={`inbox-report-section-show-more-${sectionKey}`}- >- Show more ({hiddenReportCount})- </LemonButton>- </div>- )}- </div>- )-}diff --git a/products/signals/frontend/inbox/components/cards/InboxCards.stories.tsx b/products/signals/frontend/inbox/components/cards/InboxCards.stories.tsxindex 02348bd7e72e..cfc8399510ba 100644--- a/products/signals/frontend/inbox/components/cards/InboxCards.stories.tsx+++ b/products/signals/frontend/inbox/components/cards/InboxCards.stories.tsx@@ -92,6 +92,27 @@ export const ReportCardStates: Story = {summary: 'Real but insignificant.',})}/>+ {/* Closed states keep the open-row surface, dimmed; a green or red dot on the reason tag says which. */}+ <ReportCard+ report={makeReport({+ title: 'Resolved by a merged pull request',+ priority: 'P1',+ status: SignalReportStatus.RESOLVED,+ dismissal_reason: 'pr_merged',+ source_products: ['error_tracking'],+ summary: 'Fixed and shipped; kept for reference.',+ })}+ />+ <ReportCard+ report={makeReport({+ title: 'Dismissed as intentional behavior',+ priority: 'P3',+ status: SignalReportStatus.SUPPRESSED,+ dismissal_reason: 'wontfix_intentional',+ source_products: ['session_replay'],+ summary: 'The flow works as designed.',+ })}+ /></Stack>),}diff --git a/products/signals/frontend/inbox/components/cards/ReportCard.tsx b/products/signals/frontend/inbox/components/cards/ReportCard.tsxindex dcd8fcafbb3e..86e002eca416 100644--- a/products/signals/frontend/inbox/components/cards/ReportCard.tsx+++ b/products/signals/frontend/inbox/components/cards/ReportCard.tsx@@ -1,7 +1,7 @@import clsx from 'clsx'import { router } from 'kea-router'-import { IconCheck, IconHide, IconUndo } from '@posthog/icons'+import { IconHide, IconUndo } from '@posthog/icons'import { LemonButton, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'import { TZLabel } from 'lib/components/TZLabel'@@ -105,7 +105,7 @@ export function InboxCardSourceMeta({* there is no separate open button. Dismissing and resolving live in the report detail pane and the* bulk selection bar, where what is being judged is in full view. Other surfaces that embed this* card can still opt into a row-level Dismiss via `onDismiss`. The redesign also drops the status- * and actionability chips: the section a row sits in (Needs a PR, Not actionable, ...) already says+ * and actionability chips: the state a row is in (Needs decision, Not actionable, ...) already says* what they said. With the flag off every row keeps its chips, its Dismiss button, and "Review".*/export function ReportCard({@@ -232,7 +232,17 @@ export function ReportCard({)}{outcomeLabel && (<Tooltip title={report.dismissal_note || undefined}>- <LemonTag size="small" icon={isResolved ? <IconCheck /> : <IconHide />}>+ <LemonTag+ size="small"+ icon={+ <span+ className={clsx(+ 'size-1.5 shrink-0 rounded-full',+ isResolved ? 'bg-success' : 'bg-danger'+ )}+ />+ }+ >{outcomeLabel}</LemonTag></Tooltip>@@ -249,7 +259,14 @@ export function ReportCard({)return (- <div className={inboxCardRowClassName(attached, { dashed: !hasPr })}>+ <div+ className={clsx(+ inboxCardRowClassName(attached, { dashed: !hasPr }),+ // Closed rows recede so open work stands out in the mixed flat list; hover restores+ // full opacity for reading. Matches the disabled-scout treatment in ScoutRosterCard.+ (isDismissed || isResolved) && 'opacity-55 hover:opacity-100'+ )}+ ><div className="relative flex min-w-0 flex-1">{hasPr && prNumber != null ? (<div className="absolute right-0 top-0 z-10">diff --git a/products/signals/frontend/inbox/components/detail/ReportDetailActions.tsx b/products/signals/frontend/inbox/components/detail/ReportDetailActions.tsxindex d8541fb5de3a..1b8a79db147c 100644--- a/products/signals/frontend/inbox/components/detail/ReportDetailActions.tsx+++ b/products/signals/frontend/inbox/components/detail/ReportDetailActions.tsx@@ -77,7 +77,7 @@ export function useReportDetailActions(report: SignalReport): ReportDetailActionconst staysPutOnRefund = isResolved && report.implementation_pr_merged === true// Once a verdict persists, broadcast so every mounted list reconciles against the server (the- // report leaves Needs a PR / Review and merge and joins Resolved or Dismissed), then return to+ // report leaves Needs decision / Review and merge and joins Resolved or Dismissed), then return to// the list.const leaveForList = (): void => {reportStateChanged()diff --git a/products/signals/frontend/inbox/components/shell/InboxPeoplePicker.tsx b/products/signals/frontend/inbox/components/shell/InboxPeoplePicker.tsxindex cbe7d9223df0..0b6198d56607 100644--- a/products/signals/frontend/inbox/components/shell/InboxPeoplePicker.tsx+++ b/products/signals/frontend/inbox/components/shell/InboxPeoplePicker.tsx@@ -1,6 +1,6 @@import clsx from 'clsx'-import { IconAsterisk, IconCheck } from '@posthog/icons'+import { IconAsterisk, IconCheck, IconPerson } from '@posthog/icons'import { LemonInput, Spinner } from '@posthog/lemon-ui'import { Popover } from 'lib/lemon-ui/Popover'@@ -29,6 +29,7 @@ export function InboxPeoplePicker({people,loading = false,selectedUuid,+ forYou,everyoneLabel,onPick,}: {@@ -41,6 +42,8 @@ export function InboxPeoplePicker({loading?: boolean/** `null` marks the everyone row; `undefined` marks no row at all. */selectedUuid: string | null | undefined+ /** Adds a pinned "For you" row above the everyone row (the reports scope filter uses it). */+ forYou?: { active: boolean; onPick: () => void }everyoneLabel: stringonPick: (person: InboxPerson | null) => void}): JSX.Element {@@ -62,6 +65,21 @@ export function InboxPeoplePicker({className="mb-1"/><div className="max-h-[16rem] overflow-y-auto space-y-px">+ {forYou && (+ <PersonRow+ active={forYou.active}+ onClick={forYou.onPick}+ avatar={+ <span+ className="inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-full border border-secondary text-tertiary"+ aria-hidden+ >+ <IconPerson className="text-xs" />+ </span>+ }+ label="For you"+ />+ )}<PersonRowactive={selectedUuid === null}onClick={() => onPick(null)}diff --git a/products/signals/frontend/inbox/components/shell/InboxReportFilters.tsx b/products/signals/frontend/inbox/components/shell/InboxReportFilters.tsxindex 4757d1489110..bcb8c230b1f7 100644--- a/products/signals/frontend/inbox/components/shell/InboxReportFilters.tsx+++ b/products/signals/frontend/inbox/components/shell/InboxReportFilters.tsx@@ -12,6 +12,7 @@ import {} from '../../filterOptions'import { inboxFiltersLogic } from '../../logics/inboxFiltersLogic'import { SignalReportPriority } from '../../types'+import { InboxStateFilter } from './InboxStateFilter'const ALL_PRIORITIES = null@@ -38,9 +39,8 @@ const SORT_SELECT_OPTIONS = INBOX_SORT_OPTIONS.map((option) => ({}))/**- * What narrows the report list: priority, then sort order. There is no status filter, because the- * sections below are the status split. Filter state is persisted via `inboxFiltersLogic`, and every- * section reloads on change.+ * What narrows the report list: priority, then report state, then sort order. 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.@@ -61,6 +61,7 @@ export function InboxReportFilters(): JSX.Element {renderButtonContent={() => inboxPriorityFilterLabel(priorityFilter)}data-attr="inbox-filter-priority"/>+ <InboxStateFilter /><LemonSelectsize="small"value={inboxSortOptionKey(sortField, sortDirection)}diff --git a/products/signals/frontend/inbox/components/shell/InboxScopeFilter.test.tsx b/products/signals/frontend/inbox/components/shell/InboxScopeFilter.test.tsxnew file mode 100644index 000000000000..a21368859b79--- /dev/null+++ b/products/signals/frontend/inbox/components/shell/InboxScopeFilter.test.tsx@@ -0,0 +1,55 @@+import '@testing-library/jest-dom'++import { cleanup, render, screen, waitFor } from '@testing-library/react'+import posthog from 'posthog-js'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { inboxFiltersLogic } from '../../logics/inboxFiltersLogic'+import { InboxScopeFilter } from './InboxScopeFilter'++jest.mock('posthog-js')+// The people picker isn't needed to exercise the trigger label, and it pulls in a popover + avatars.+jest.mock('./InboxPeoplePicker', () => ({ InboxPeoplePicker: () => null }))++describe('InboxScopeFilter', () => {+ beforeEach(() => {+ ;(posthog.capture as jest.Mock).mockClear()+ // Roster holds one teammate; the backend returns a flat `{ uuid: { name, email } }` map.+ useMocks({+ get: {+ '/api/projects/:team_id/signals/reports/available_reviewers': {+ 'uuid-ada': { name: 'Ada', email: '[email protected]' },+ },+ },+ })+ initKeaTests()+ })++ afterEach(cleanup)++ // The trigger's accessible name must carry the scope. If the LemonButton tooltip leaks into+ // aria-label instead, a screen reader hears the help sentence and never the active scope.+ it('names the active scope for assistive tech instead of the help tooltip', () => {+ inboxFiltersLogic.mount()+ render(<InboxScopeFilter />)++ expect(screen.getByLabelText('Report scope: For you')).toBeInTheDocument()+ })++ // Scoping to a teammate the roster hasn't loaded (search-filtered, or past the 100-row cap) must+ // not leave the previous teammate's name on the trigger — the data underneath is already the new+ // teammate's, so a stale name misreports whose reports are shown.+ it('drops the cached label when the scope moves to an off-roster teammate', async () => {+ inboxFiltersLogic.mount()+ render(<InboxScopeFilter />)++ inboxFiltersLogic.actions.setScope('teammate:uuid-ada')+ await waitFor(() => expect(screen.getByText('Ada')).toBeInTheDocument())++ inboxFiltersLogic.actions.setScope('teammate:uuid-off-roster')+ await waitFor(() => expect(screen.getByText('Teammate')).toBeInTheDocument())+ expect(screen.queryByText('Ada')).toBeNull()+ })+})diff --git a/products/signals/frontend/inbox/components/shell/InboxScopeFilter.tsx b/products/signals/frontend/inbox/components/shell/InboxScopeFilter.tsxnew file mode 100644index 000000000000..815ae9fb99c6--- /dev/null+++ b/products/signals/frontend/inbox/components/shell/InboxScopeFilter.tsx@@ -0,0 +1,116 @@+import { useActions, useValues } from 'kea'+import { useEffect, useState } from 'react'++import { IconChevronDown } from '@posthog/icons'+import { LemonButton } from '@posthog/lemon-ui'++import { userLogic } from 'scenes/userLogic'++import { isTeammateInboxScope, parseTeammateInboxScope, teammateInboxScope } from '../../inboxMembership'+import { inboxFiltersLogic } from '../../logics/inboxFiltersLogic'+import { INBOX_SCOPE_ENTIRE_PROJECT, INBOX_SCOPE_FOR_YOU, InboxScope } from '../../types'+import { InboxPeoplePicker } from './InboxPeoplePicker'++/**+ * Single-dropdown reviewer scope for the flat Reports list: one trigger that names the current+ * scope and opens the shared people picker with "For you" pinned on top, then "Entire project",+ * then each teammate. "For you" is the default scope; a user with no reports suggested to them is+ * auto-switched to "Entire project" (see `shouldDefaultToEntireProject`). The legacy layout keeps+ * the two-segment `InboxScopeSelect` until the redesign flag replaces it. Scope is persisted via+ * `inboxFiltersLogic`; teammates come from its shared `availableReviewers` loader.+ */+export function InboxScopeFilter(): JSX.Element {+ const { scope, availableReviewers: reviewers, availableReviewersLoading } = useValues(inboxFiltersLogic)+ const { setScope, searchAvailableReviewers } = useActions(inboxFiltersLogic)+ const { user } = useValues(userLogic)+ const [open, setOpen] = useState(false)+ const [search, setSearch] = useState('')+ // External reference (callback ref → state so the Popover re-anchors once mounted).+ const [referenceEl, setReferenceEl] = useState<HTMLDivElement | null>(null)+ // Remember the selected teammate's label so the trigger stays correct even while a search+ // query has filtered them out of the server-returned `reviewers` list. Keep the uuid alongside+ // it: a scope change to a different teammate the roster hasn't loaded (search-filtered, or past+ // the 100-row cap) must not fall back to the previous teammate's name.+ const [knownTeammate, setKnownTeammate] = useState<{ uuid: string; label: string } | null>(null)++ const isForYou = scope === INBOX_SCOPE_FOR_YOU+ const selectedTeammateUuid = isTeammateInboxScope(scope) ? parseTeammateInboxScope(scope) : null+ const selectedTeammate = reviewers.find((r) => r.user_uuid === selectedTeammateUuid)+ const selectedTeammateLabel = selectedTeammate ? selectedTeammate.name || selectedTeammate.email : null++ useEffect(() => {+ if (selectedTeammateUuid && selectedTeammateLabel) {+ setKnownTeammate({ uuid: selectedTeammateUuid, label: selectedTeammateLabel })+ }+ }, [selectedTeammateUuid, selectedTeammateLabel])++ // Only reuse the cached label when it names the currently-scoped teammate.+ const cachedTeammateLabel =+ knownTeammate && knownTeammate.uuid === selectedTeammateUuid ? knownTeammate.label : null++ const triggerLabel = isForYou+ ? 'For you'+ : selectedTeammateUuid+ ? (selectedTeammateLabel ?? cachedTeammateLabel ?? 'Teammate')+ : 'Entire project'++ const pick = (next: InboxScope, label?: string): void => {+ const nextUuid = parseTeammateInboxScope(next)+ if (label && nextUuid) {+ setKnownTeammate({ uuid: nextUuid, label })+ }+ setScope(next)+ setOpen(false)+ setSearch('')+ searchAvailableReviewers('')+ }++ return (+ <>+ <div ref={setReferenceEl} className="inline-flex">+ <LemonButton+ size="small"+ type="secondary"+ onClick={() => setOpen((v) => !v)}+ sideIcon={<IconChevronDown className="text-tertiary" />}+ tooltip="See the reports suggested to you, every report in the project, or a teammate's"+ // Name the active scope for assistive tech. Without this, LemonButton copies the+ // string tooltip into aria-label, so a screen reader hears the help text and never+ // the current scope.+ aria-label={`Report scope: ${triggerLabel}`}+ data-attr="inbox-scope-filter"+ >+ <span className="max-w-[160px] truncate">{triggerLabel}</span>+ </LemonButton>+ </div>+ <InboxPeoplePicker+ visible={open}+ referenceElement={referenceEl}+ onClose={() => setOpen(false)}+ search={search}+ onSearch={(value) => {+ setSearch(value)+ searchAvailableReviewers(value)+ }}+ // The pinned "For you" row already stands for the signed-in user, so their own+ // roster row would be a second control writing a different scope for the same view.+ people={reviewers+ .filter((reviewer) => reviewer.user_uuid !== user?.uuid)+ .map((reviewer) => ({+ uuid: reviewer.user_uuid,+ name: reviewer.name,+ email: reviewer.email,+ }))}+ loading={availableReviewersLoading}+ selectedUuid={scope === INBOX_SCOPE_ENTIRE_PROJECT ? null : (selectedTeammateUuid ?? undefined)}+ forYou={{ active: isForYou, onPick: () => pick(INBOX_SCOPE_FOR_YOU) }}+ everyoneLabel="Entire project"+ onPick={(person) =>+ person+ ? pick(teammateInboxScope(person.uuid), person.name || person.email)+ : pick(INBOX_SCOPE_ENTIRE_PROJECT)+ }+ />+ </>+ )+}diff --git a/products/signals/frontend/inbox/components/shell/InboxStateFilter.tsx b/products/signals/frontend/inbox/components/shell/InboxStateFilter.tsxnew file mode 100644index 000000000000..a9232539fdbc--- /dev/null+++ b/products/signals/frontend/inbox/components/shell/InboxStateFilter.tsx@@ -0,0 +1,86 @@+import { useActions, useValues } from 'kea'+import { useState } from 'react'++import { LemonButton, LemonCheckbox, LemonDropdown, LemonTag } from '@posthog/lemon-ui'++import { inboxSceneLogic } from '../../inboxSceneLogic'+import { inboxFiltersLogic } from '../../logics/inboxFiltersLogic'+import {+ INBOX_REPORT_SECTION_DESCRIPTION,+ INBOX_REPORT_SECTION_KEYS,+ INBOX_REPORT_SECTION_LABEL,+ INBOX_REPORT_SECTION_TAG,+ INBOX_STAFF_ONLY_REPORT_SECTION_KEYS,+} from '../../types'++/**+ * Multi-select report-state filter for the flat Reports list: one checkbox per state (Needs decision,+ * Review and merge, Resolved, Dismissed, plus Not actionable for staff). The open-work states are+ * selected by default (see DEFAULT_STATE_FILTER); an empty selection means every state, so the+ * trigger reads "All statuses" then.+ */+export function InboxStateFilter(): JSX.Element {+ const { isStaff } = useValues(inboxSceneLogic)+ const { stateFilter, visibleStateFilter } = useValues(inboxFiltersLogic)+ const { toggleState } = useActions(inboxFiltersLogic)+ const [visible, setVisible] = useState(false)++ const options = INBOX_REPORT_SECTION_KEYS.filter(+ (key) => isStaff || !INBOX_STAFF_ONLY_REPORT_SECTION_KEYS.includes(key)+ )+ // Label from the visible selection: a shared link can carry the staff-only state, and the+ // trigger must not read "Not actionable" (or an inflated count) for a state whose checkbox the+ // dropdown hides and that does not narrow the list.+ const label =+ visibleStateFilter.length === 0+ ? 'All statuses'+ : visibleStateFilter.length === 1+ ? INBOX_REPORT_SECTION_LABEL[visibleStateFilter[0]]+ : `${visibleStateFilter.length} statuses`++ return (+ <LemonDropdown+ closeOnClickInside={false}+ visible={visible}+ onVisibilityChange={setVisible}+ matchWidth={false}+ actionable+ placement="bottom-start"+ overlay={+ <div className="flex flex-col gap-px p-1">+ {options.map((key) => {+ const tag = INBOX_REPORT_SECTION_TAG[key]+ return (+ <LemonCheckbox+ key={key}+ size="small"+ checked={stateFilter.includes(key)}+ onChange={() => toggleState(key)}+ className="rounded px-1.5 py-1 hover:bg-surface-secondary"+ fullWidth+ label={+ <span+ className="flex items-center gap-1.5"+ title={INBOX_REPORT_SECTION_DESCRIPTION[key]}+ >+ {INBOX_REPORT_SECTION_LABEL[key]}+ {tag && (+ <LemonTag type="completion" size="small">+ {tag}+ </LemonTag>+ )}+ </span>+ }+ data-attr={`inbox-filter-state-${key}`}+ />+ )+ })}+ </div>+ }+ >+ <LemonButton size="small" type="secondary" data-attr="inbox-filter-state">+ {label}+ </LemonButton>+ </LemonDropdown>+ )+}diff --git a/products/signals/frontend/inbox/components/shell/InboxTabBar.tsx b/products/signals/frontend/inbox/components/shell/InboxTabBar.tsxindex 178d74f32d88..5bc2f8ee62c6 100644--- a/products/signals/frontend/inbox/components/shell/InboxTabBar.tsx+++ b/products/signals/frontend/inbox/components/shell/InboxTabBar.tsx@@ -9,7 +9,7 @@ import { inboxSceneLogic } from '../../inboxSceneLogic'import { INBOX_TAB_KEYS, INBOX_TAB_LABEL, InboxTabKey } from '../../types'/**- * Page tab bar: Reports / Scouts / Settings. The report sections (Review and merge / Needs a PR /+ * Page tab bar: Reports / Scouts / Settings. The report sections (Review and merge / Needs decision /* Resolved) live inside the Reports tab, so no counts sit here.*/export function InboxTabBar(): JSX.Element {diff --git a/products/signals/frontend/inbox/components/tabs/InboxTabs.stories.tsx b/products/signals/frontend/inbox/components/tabs/InboxTabs.stories.tsxindex 8811158540e0..c88634e0f034 100644--- a/products/signals/frontend/inbox/components/tabs/InboxTabs.stories.tsx+++ b/products/signals/frontend/inbox/components/tabs/InboxTabs.stories.tsx@@ -10,16 +10,15 @@ import { mswDecorator } from '~/mocks/browser'import { pullRequestReports, reportTabReports } from '../../__mocks__/inboxMocks'import { inboxSceneLogic } from '../../inboxSceneLogic'-import { DEFAULT_OPEN_SECTIONS, inboxReportSectionsLogic } from '../../logics/inboxReportSectionsLogic'-import { INBOX_REPORT_SECTION_KEYS, SignalReport, SignalRun } from '../../types'+import { SignalReport, SignalRun } from '../../types'import { PullRequestsTab } from './PullRequestsTab'import { ReportsTab } from './ReportsTab'import { ReportsTabLegacy } from './ReportsTabLegacy'import { RunsTab } from './RunsTab'-// Stories for the inbox tab bodies. The Reports tab loads each section via `reportListLogic`, so it-// gets an mswDecorator that mocks the reports list endpoint; the Runs panel is prop-driven and-// receives mock runs directly. Use these to polish section density and the run-card design.+// Stories for the inbox tab bodies. The Reports tab loads each report state via `reportListLogic`,+// so it gets an mswDecorator that mocks the reports list endpoint; the Runs panel is prop-driven+// and receives mock runs directly. Use these to polish list density and the run-card design.const SAMPLE_RUNS: SignalRun[] = [{@@ -62,19 +61,14 @@ function reportsListDecorator(reports: SignalReport[]): Decorator {})}-// One mocked endpoint feeds every section, so each renders the same rows — enough to judge the-// section rhythm, which is what these stories are for.-function ReportsTabStory({ expandAll = false }: { expandAll?: boolean }): JSX.Element {+// One mocked endpoint feeds every report state, so the same rows come back for each state's+// request and the flat list deduplicates them — enough to judge the list rhythm, which is what+// these stories are for.+function ReportsTabStory({ searchParams }: { searchParams?: Record<string, string> }): JSX.Element {useMountedLogic(inboxSceneLogic)- const sectionsLogic = useMountedLogic(inboxReportSectionsLogic)useEffect(() => {- router.actions.push(urls.inbox('reports'))- if (expandAll) {- INBOX_REPORT_SECTION_KEYS.filter((key) => !DEFAULT_OPEN_SECTIONS[key]).forEach((key) =>- sectionsLogic.actions.toggleSection(key)- )- }- }, [expandAll, sectionsLogic])+ router.actions.push(urls.inbox('reports'), searchParams ?? {})+ }, [searchParams])return (<div className="bg-primary min-h-screen"><ReportsTab />@@ -96,19 +90,19 @@ export default metatype Story = StoryObj-// The default arrangement: Needs a PR and Review and merge open, Resolved collapsed.+// The default view: one flat list over the default-selected open-work states.export const Reports: Story = {decorators: [reportsListDecorator(reportTabReports)],render: () => <ReportsTabStory />,}-// Every section open, including the ones that start collapsed.-export const ReportsAllSectionsExpanded: Story = {+// The state filter narrowing the list to one state via the shared `state` URL param.+export const ReportsStateFiltered: Story = {decorators: [reportsListDecorator(pullRequestReports)],- render: () => <ReportsTabStory expandAll />,+ render: () => <ReportsTabStory searchParams={{ state: 'monitoring' }} />,}-// Nothing anywhere: the whole-list empty state rather than a per-section one.+// Nothing anywhere: the whole-list empty state.export const ReportsEmpty: Story = {decorators: [reportsListDecorator([])],render: () => <ReportsTabStory />,diff --git a/products/signals/frontend/inbox/components/tabs/ReportsTab.test.tsx b/products/signals/frontend/inbox/components/tabs/ReportsTab.test.tsxindex 1d2b0a8a364a..1d0db13cb4db 100644--- a/products/signals/frontend/inbox/components/tabs/ReportsTab.test.tsx+++ b/products/signals/frontend/inbox/components/tabs/ReportsTab.test.tsx@@ -13,16 +13,20 @@ import { initKeaTests } from '~/test/init'import { INBOX_EVENTS } from '../../inboxAnalytics'import { inboxFiltersLogic } from '../../logics/inboxFiltersLogic'-import { INBOX_SCOPE_ENTIRE_PROJECT } from '../../types'+import { INBOX_SCOPE_ENTIRE_PROJECT, InboxReportSectionKey, SignalReport, SignalReportStatus } from '../../types'import { ReportsTab } from './ReportsTab'jest.mock('posthog-js')-// The sections, filters, and bulk bar each pull in their own endpoints; this is about what the tab-// reports for the list as a whole.-jest.mock('../InboxReportSection', () => ({- InboxReportSection: ({ sectionKey }: { sectionKey: string }) => <div data-attr={`section-${sectionKey}`} />,+// The filters, scope, and bulk bar each pull in their own endpoints; these tests are about what the+// flat list renders and reports as a whole. The card mock keeps a row identifiable without the full+// card DOM.+jest.mock('../cards/ReportCard', () => ({+ ReportCard: ({ report, sectionKey }: { report: SignalReport; sectionKey: InboxReportSectionKey }) => (+ <div data-attr={`report-card-${report.id}`} data-section={sectionKey} />+ ),}))jest.mock('../shell/InboxReportFilters', () => ({ InboxReportFilters: () => null }))+jest.mock('../shell/InboxScopeFilter', () => ({ InboxScopeFilter: () => null }))jest.mock('../shell/InboxBulkSelectionBar', () => ({ InboxBulkSelectionBar: () => null }))jest.mock('../SelfDrivingInstallingHint', () => ({ SelfDrivingInstallingHint: () => null }))@@ -31,7 +35,7 @@ interface SectionCountStub {count: number}-// One count per section's fixed filter, so the summed total is unambiguous.+// One count per state's fixed filter, so the summed total is unambiguous.const COUNT_BY_FILTER: SectionCountStub[] = [{ match: (p) => p.get('has_implementation_pr') === 'true', count: 4 },{ match: (p) => p.get('has_implementation_pr') === 'false', count: 7 },@@ -39,7 +43,7 @@ const COUNT_BY_FILTER: SectionCountStub[] = []// Only `ready` + `not_actionable` reports: the pipeline's actionability judgment leaves the status-// alone, so nothing lands in the three counted sections.+// alone, so nothing lands in the counted states.const ONLY_NOT_ACTIONABLE: SectionCountStub[] = [{ match: (p) => p.get('actionability') === 'not_actionable' && !p.has('has_implementation_pr'), count: 3 },]@@ -57,9 +61,59 @@ function mockReportCounts(stubs: SectionCountStub[]): void {})}+function makeReport(id: string, status: SignalReportStatus): SignalReport {+ return {+ id,+ title: `Report ${id}`,+ summary: 'summary',+ status,+ total_weight: 0,+ signal_count: 1,+ relevant_user_count: null,+ artefact_count: 0,+ is_suggested_reviewer: false,+ priority: 'P2',+ created_at: '2026-06-11T10:00:00Z',+ updated_at: '2026-06-11T10:00:00Z',+ } satisfies SignalReport+}++// Rows keyed off each state's fixed filter, so which state contributed a row is observable. The+// optional gate holds the Resolved state's rows response (not its `limit=1` count) open, so a test+// can assert what the list shows while that state is still loading its first page.+function mockReportRows(resolvedRowsGate?: { block: Promise<void>; onRequest: () => void }): void {+ const withPr = makeReport('with-pr', SignalReportStatus.READY)+ const needsPr = makeReport('needs-pr', SignalReportStatus.READY)+ const resolved = makeReport('resolved', SignalReportStatus.RESOLVED)+ useMocks({+ get: {+ '/api/projects/:team_id/signals/reports/available_reviewers': {},+ '/api/projects/:team_id/signals/reports/': async ({ request }) => {+ const params = new URL(request.url).searchParams+ const isResolved = (params.get('status') ?? '').includes('resolved')+ if (isResolved && params.get('limit') !== '1' && resolvedRowsGate) {+ resolvedRowsGate.onRequest()+ await resolvedRowsGate.block+ }+ const results =+ params.get('has_implementation_pr') === 'true'+ ? [withPr]+ : params.get('has_implementation_pr') === 'false'+ ? [needsPr]+ : isResolved+ ? [resolved]+ : []+ return [200, { count: results.length, next: null, previous: null, results }]+ },+ },+ })+}+describe('ReportsTab', () => {beforeEach(() => {;(posthog.capture as jest.Mock).mockClear()+ // The filters persist to localStorage, so one test's toggles must not leak into the next.+ localStorage.clear()mockReportCounts(COUNT_BY_FILTER)initKeaTests()})@@ -74,24 +128,24 @@ describe('ReportsTab', () => {})}- // The sections all render at once, so the naive wiring fires one `Inbox viewed` per section and- // triples every visit in the activation funnel.+ // All the states load at once, so the naive wiring fires one `Inbox viewed` per state and+ // multiplies every visit in the activation funnel.it('fires Inbox viewed once for the whole list', async () => {render(<ReportsTab />)await waitFor(() => {const viewed = (posthog.capture as jest.Mock).mock.calls.filter(([event]) => event === INBOX_EVENTS.VIEWED)expect(viewed).toHaveLength(1)- // Needs a PR + Review and merge + Resolved + Dismissed. Not actionable is staff-only triage.+ // Needs decision + Review and merge + Resolved + Dismissed. Not actionable is staff-only triage.expect(viewed[0][1]).toMatchObject({ tab: 'reports', total_count: 13, is_empty: false })})})- // The empty verdict used to be taken over the three counted sections only, so a staff user on a- // project whose reports were all judged not actionable was told "nothing yet" while the section- // built to review them was never mounted.+ // The empty verdict must cover every state the current user can see, not only the counted+ // ones: a staff user on a project whose reports are all judged not actionable still has work+ // to review, so "nothing yet" would be wrong for them and right for everyone else.it.each([- { name: 'staff sees Not actionable when it is the only section with reports', isStaff: true, empty: false },+ { name: 'staff is not told "nothing yet" when only Not actionable has reports', isStaff: true, empty: false },{ name: 'non-staff sees the empty state for the same project', isStaff: false, empty: true },])('$name', async ({ isStaff, empty }) => {mockReportCounts(ONLY_NOT_ACTIONABLE)@@ -103,15 +157,22 @@ describe('ReportsTab', () => {await waitForCountsToSettle()expect(screen.queryByText('Nothing in your inbox yet') !== null).toBe(empty)- expect(document.querySelector('[data-attr="section-not-actionable"]') !== null).toBe(!empty)})// "Nothing yet" claims the project has no reports. A search or scope that matches nothing must- // not make that claim, or the user loses the filter bar's own per-section feedback.+ // not make that claim, or the user loses the way back to the full list.it.each([- { name: 'a search that matches nothing', setUp: () => inboxFiltersLogic.actions.setSearchQuery('zzz') },- { name: 'the For-you scope', setUp: () => inboxFiltersLogic.actions.setScope('for-you') },- ])('keeps the sections when $name is active', async ({ setUp }) => {+ {+ name: 'a search that matches nothing',+ setUp: () => inboxFiltersLogic.actions.setSearchQuery('zzz'),+ copy: 'No reports match the current filters.',+ },+ {+ name: 'the For-you scope',+ setUp: () => inboxFiltersLogic.actions.setScope('for-you'),+ copy: 'No reports suggested for you yet. Switch the scope to see the entire project.',+ },+ ])('keeps the filter-aware copy when $name is active', async ({ setUp, copy }) => {mockReportCounts([])inboxFiltersLogic.mount()setUp()@@ -119,7 +180,82 @@ describe('ReportsTab', () => {render(<ReportsTab />)await waitForCountsToSettle()- expect(document.querySelector('[data-attr="section-needs-decision"]')).not.toBeNull()+ await waitFor(() => expect(screen.getByText(copy)).toBeInTheDocument())expect(screen.queryByText('Nothing in your inbox yet')).toBeNull()})++ // The whole point of the flat list: one merged run over the selected states. The default+ // selection is the open work (Review and merge + Needs decision); the state filter widens it+ // to the closed states and narrows it back down.+ it('shows the open-work states by default and follows the state filter', async () => {+ let releaseResolvedRows: () => void = () => {}+ let resolvedRowsRequested = false+ mockReportRows({+ block: new Promise((resolve) => {+ releaseResolvedRows = resolve+ }),+ onRequest: () => {+ resolvedRowsRequested = true+ },+ })+ inboxFiltersLogic.mount()+ inboxFiltersLogic.actions.setScope(INBOX_SCOPE_ENTIRE_PROJECT)++ render(<ReportsTab />)++ await waitFor(() => {+ expect(document.querySelector('[data-attr="report-card-with-pr"]')).not.toBeNull()+ expect(document.querySelector('[data-attr="report-card-needs-pr"]')).not.toBeNull()+ })+ expect(document.querySelector('[data-attr="report-card-resolved"]')).toBeNull()++ inboxFiltersLogic.actions.toggleState('resolved')++ // The loaded rows must stay on screen while the newly selected state fetches its first+ // page: falling back to the first-load skeleton here wipes the list on every state toggle.+ await waitFor(() => expect(resolvedRowsRequested).toBe(true))+ expect(document.querySelector('[data-attr="report-card-with-pr"]')).not.toBeNull()+ expect(document.querySelector('[data-attr="report-card-needs-pr"]')).not.toBeNull()++ releaseResolvedRows()+ await waitFor(() => {+ expect(document.querySelector('[data-attr="report-card-resolved"]')).not.toBeNull()+ })++ inboxFiltersLogic.actions.toggleState('needs-decision')++ await waitFor(() => {+ expect(document.querySelector('[data-attr="report-card-needs-pr"]')).toBeNull()+ })+ expect(document.querySelector('[data-attr="report-card-with-pr"]')).not.toBeNull()+ })++ // A shared link or persisted storage can carry `state=not-actionable`, a staff-only state the+ // filter control offers no checkbox for. If it narrowed the list for a non-staff user, they+ // would be stuck on an empty view with no way to clear it.+ it('does not trap a non-staff user on a staff-only state filter', async () => {+ mockReportRows()+ userLogic.actions.loadUserSuccess({ ...MOCK_DEFAULT_USER, is_staff: false })+ inboxFiltersLogic.mount()+ // A shared link carrying only the staff-only state, hydrated the way urlToAction applies it.+ inboxFiltersLogic.actions.setFilters({+ scope: INBOX_SCOPE_ENTIRE_PROJECT,+ sourceProductFilter: [],+ scoutFilter: [],+ priorityFilter: [],+ stateFilter: ['not-actionable'],+ sortField: 'priority',+ sortDirection: 'asc',+ searchQuery: '',+ })++ render(<ReportsTab />)++ await waitFor(() => {+ expect(document.querySelector('[data-attr="report-card-with-pr"]')).not.toBeNull()+ expect(document.querySelector('[data-attr="report-card-needs-pr"]')).not.toBeNull()+ expect(document.querySelector('[data-attr="report-card-resolved"]')).not.toBeNull()+ })+ expect(screen.queryByText('No reports match the current filters.')).toBeNull()+ })})diff --git a/products/signals/frontend/inbox/components/tabs/ReportsTab.tsx b/products/signals/frontend/inbox/components/tabs/ReportsTab.tsxindex e7f3036c4942..0452406e5348 100644--- a/products/signals/frontend/inbox/components/tabs/ReportsTab.tsx+++ b/products/signals/frontend/inbox/components/tabs/ReportsTab.tsx@@ -1,5 +1,5 @@import { useValues } from 'kea'-import { JSX, useEffect, useRef } from 'react'+import { JSX, useCallback, useEffect, useRef } from 'react'import { IconNotebook } from '@posthog/icons'import { LemonButton } from '@posthog/lemon-ui'@@ -11,27 +11,30 @@ import { urls } from 'scenes/urls'import { captureInboxViewed } from '../../inboxAnalytics'import { inboxSceneLogic } from '../../inboxSceneLogic'-import { inboxFiltersLogic } from '../../logics/inboxFiltersLogic'-import { INBOX_REPORT_SECTION_LIST_PARAMS, reportListLogic } from '../../logics/reportListLogic'+import { inboxFiltersLogic, isDefaultStateFilter } from '../../logics/inboxFiltersLogic'+import { reportListLogic, sectionListLogicProps } from '../../logics/reportListLogic'import {- INBOX_REPORT_SECTION_KEYS,INBOX_SCOPE_ENTIRE_PROJECT,- INBOX_STAFF_ONLY_REPORT_SECTION_KEYS,+ INBOX_SCOPE_FOR_YOU,InboxReportSectionKey,+ InboxScope,SignalReport,} from '../../types'+import { mergeReportRows, selectedFlatListSections } from '../../utils/flatReportList'+import { CardSkeleton } from '../cards/CardSkeleton'+import { ReportCard } from '../cards/ReportCard'import { InboxWaitingForWork } from '../emptyState/InboxWaitingForWork'-import { InboxReportSection } from '../InboxReportSection'import { SelfDrivingInstallingHint } from '../SelfDrivingInstallingHint'import { InboxBulkSelectionBar } from '../shell/InboxBulkSelectionBar'import { InboxReportFilters } from '../shell/InboxReportFilters'-import { InboxScopeSelect } from '../shell/InboxScopeSelect'+import { InboxScopeFilter } from '../shell/InboxScopeFilter'+import { useReportImpressions } from '../useReportImpressions'/**- * The sections that make up "the inbox" for the `Inbox viewed` event. Not actionable is left out: it+ * The states that make up "the inbox" for the `Inbox viewed` event. Not actionable is left out: it* is a staff triage surface, and counting it would report a non-empty inbox on a project that has* surfaced nothing worth acting on. The empty-state verdict is a separate question, answered over- * the sections the current user can actually see.+ * the states the current user can actually see.*/const COUNTED_SECTION_KEYS = ['needs-decision', 'monitoring', 'resolved', 'dismissed'] as const@@ -40,96 +43,64 @@ type CountedSectionKey = (typeof COUNTED_SECTION_KEYS)[number]interface SectionListState {count: number | nullcountLoading: boolean- visibleReports: SignalReport[]+ reports: SignalReport[]+ isLoaded: boolean+ reportsLoadFailed: boolean+ pageLoadFailed: boolean+ reportsResponseLoading: boolean+ hasMore: boolean}/**- * Every section's header count and rendered rows, keyed by section. All five logics are mounted- * regardless of who is looking, so the hooks never change shape when the staff flag resolves;- * callers decide which sections matter to them.- ** Read one value at a time rather than spreading what `useValues` returns: it hands back a proxy* whose properties are subscribing getters, and spreading it yields an empty object — silently, and* with a type that still claims every value is there.*/-function useSectionStates(): Record<InboxReportSectionKey, SectionListState> {- const needsDecisionProps = {- sectionKey: 'needs-decision' as const,- listParams: INBOX_REPORT_SECTION_LIST_PARAMS['needs-decision'],- }- const monitoringProps = {- sectionKey: 'monitoring' as const,- listParams: INBOX_REPORT_SECTION_LIST_PARAMS.monitoring,- }- const resolvedProps = { sectionKey: 'resolved' as const, listParams: INBOX_REPORT_SECTION_LIST_PARAMS.resolved }- const dismissedProps = { sectionKey: 'dismissed' as const, listParams: INBOX_REPORT_SECTION_LIST_PARAMS.dismissed }- const notActionableProps = {- sectionKey: 'not-actionable' as const,- listParams: INBOX_REPORT_SECTION_LIST_PARAMS['not-actionable'],- }-- const {- count: needsDecisionCount,- countLoading: needsDecisionCountLoading,- visibleReports: needsDecisionReports,- } = useValues(reportListLogic(needsDecisionProps))- const {- count: monitoringCount,- countLoading: monitoringCountLoading,- visibleReports: monitoringReports,- } = useValues(reportListLogic(monitoringProps))- const {- count: resolvedCount,- countLoading: resolvedCountLoading,- visibleReports: resolvedReports,- } = useValues(reportListLogic(resolvedProps))- const {- count: dismissedCount,- countLoading: dismissedCountLoading,- visibleReports: dismissedReports,- } = useValues(reportListLogic(dismissedProps))+function useSectionState(sectionKey: InboxReportSectionKey): SectionListState {const {- count: notActionableCount,- countLoading: notActionableCountLoading,- visibleReports: notActionableReports,- } = useValues(reportListLogic(notActionableProps))+ count,+ countLoading,+ reports,+ isLoaded,+ reportsLoadFailed,+ pageLoadFailed,+ reportsResponseLoading,+ hasMore,+ } = useValues(reportListLogic(sectionListLogicProps(sectionKey)))+ return {+ count,+ countLoading,+ reports,+ isLoaded,+ reportsLoadFailed,+ pageLoadFailed,+ reportsResponseLoading,+ hasMore,+ }+}+/**+ * Every state's count and loaded rows, keyed by state. All five logics are mounted regardless of+ * who is looking or which states the filter selects, so the hooks never change shape when the+ * staff flag resolves or a checkbox toggles; callers decide which states matter to them.+ */+function useSectionStates(): Record<InboxReportSectionKey, SectionListState> {return {- 'needs-decision': {- count: needsDecisionCount,- countLoading: needsDecisionCountLoading,- visibleReports: needsDecisionReports,- },- monitoring: {- count: monitoringCount,- countLoading: monitoringCountLoading,- visibleReports: monitoringReports,- },- resolved: {- count: resolvedCount,- countLoading: resolvedCountLoading,- visibleReports: resolvedReports,- },- dismissed: {- count: dismissedCount,- countLoading: dismissedCountLoading,- visibleReports: dismissedReports,- },- 'not-actionable': {- count: notActionableCount,- countLoading: notActionableCountLoading,- visibleReports: notActionableReports,- },+ monitoring: useSectionState('monitoring'),+ 'needs-decision': useSectionState('needs-decision'),+ resolved: useSectionState('resolved'),+ dismissed: useSectionState('dismissed'),+ 'not-actionable': useSectionState('not-actionable'),}}/**- * `Inbox viewed`, fired once per Reports mount as soon as every counted section's header count has- * settled. One event per visit, as before the sections replaced the view tabs — but the reader now- * sees every section at once, so it carries the whole list rather than one view's slice.+ * `Inbox viewed`, fired once per Reports mount as soon as every counted state's count has settled.+ * One event per visit, carrying the whole loaded list.*/function useInboxViewedEvent(sections: Record<CountedSectionKey, SectionListState>): void {- const { hasActiveFilters, sourceProductFilter, priorityFilter, scope } = useValues(inboxFiltersLogic)+ const { hasActiveFilters, sourceProductFilter, priorityFilter, visibleStateFilter, scope } =+ useValues(inboxFiltersLogic)// The list stays mounted (hidden) while a report/scout detail is open, so gate the view event on// the list actually being the visible surface — otherwise a deep-link to a report fires a phantom// `Inbox viewed` and then suppresses the real one when the user navigates back to the list.@@ -155,22 +126,31 @@ function useInboxViewedEvent(sections: Record<CountedSectionKey, SectionListStat}firedRef.current = truecaptureInboxViewed({- // pinned: `tab` names the inbox page tab. Before the sections landed it named the report- // view, which is no longer a surface of its own.+ // pinned: analytics property. `tab` names the inbox page tab; dashboards group on it.tab: 'reports',- reports: COUNTED_SECTION_KEYS.flatMap((key) => sections[key].visibleReports),+ reports: COUNTED_SECTION_KEYS.flatMap((key) => sections[key].reports),totalCount: COUNTED_SECTION_KEYS.reduce((sum, key) => sum + (sections[key].count ?? 0), 0),pullsTabCount: sections.monitoring.count,reportsTabCount: sections['needs-decision'].count,hasActiveFilters,sourceProductFilter,priorityFilter,+ stateFilter: visibleStateFilter,scope,})- }, [listVisible, settled, sections, hasActiveFilters, sourceProductFilter, priorityFilter, scope])+ }, [+ listVisible,+ settled,+ sections,+ hasActiveFilters,+ sourceProductFilter,+ priorityFilter,+ visibleStateFilter,+ scope,+ ])}-/** Nothing has reached the inbox yet — the whole list is empty, not just one section. */+/** Nothing has reached the inbox yet — the whole list is empty, not just one state. */function ReportsEmptyState(): JSX.Element {const { featureFlags } = useValues(featureFlagLogic)if (featureFlags[FEATURE_FLAGS.INBOX_SELF_DRIVING_EMPTY_STATE] === 'empty-state') {@@ -193,30 +173,135 @@ function ReportsEmptyState(): JSX.Element {)}+function emptyListCopy(scope: InboxScope, narrowed: boolean): string {+ if (narrowed) {+ return 'No reports match the current filters.'+ }+ if (scope === INBOX_SCOPE_FOR_YOU) {+ return 'No reports suggested for you yet. Switch the scope to see the entire project.'+ }+ return 'No reports here yet.'+}+/**- * The Reports tab: one toolbar over a single column of collapsible sections (Needs a PR / Review and- * merge / Resolved / Dismissed, plus Not actionable for staff). Each section owns its own filtered request,- * count, and paging via the keyed `reportListLogic`, while the toolbar, reviewer scope, and bulk+ * The Reports tab: one toolbar over a single flat list of report cards. Each report state (Needs a+ * PR / Review and merge / Resolved / Dismissed, plus Not actionable for staff) is its own filtered+ * request via the keyed `reportListLogic`; the list merges the selected states' rows, and the+ * toolbar's state filter picks which ones those are. The toolbar, reviewer scope, and bulk* selection are shared across all of them.*/export function ReportsTab(): JSX.Element {const { isStaff } = useValues(inboxSceneLogic)- const { hasActiveFilters, scope } = useValues(inboxFiltersLogic)+ const { hasActiveFilters, visibleStateFilter, scope, sortField, sortDirection } = useValues(inboxFiltersLogic)const sections = useSectionStates()useInboxViewedEvent(sections)- const visibleSections: InboxReportSectionKey[] = INBOX_REPORT_SECTION_KEYS.filter(- (key) => isStaff || !INBOX_STAFF_ONLY_REPORT_SECTION_KEYS.includes(key)- )+ const visibleSections = selectedFlatListSections([], isStaff)+ // The state filter narrows which states' rows the list shows; an empty selection means all of+ // them. `visibleStateFilter` already drops states the user cannot see (a staff-only state from+ // a shared link or persisted storage), so a hidden state can never leave this empty and a+ // non-staff user who opens a `state=not-actionable` link still sees the full list.+ const selectedSections = selectedFlatListSections(visibleStateFilter, isStaff)+// "Nothing yet" is a claim about the whole project, so it only holds with no filters and the- // project-wide scope; a narrowed view that matches nothing shows the sections with their own- // per-section copy instead. The verdict is over the sections this user can see, so staff still- // reach Not actionable when it is the only section with reports. Hold the sections until every- // count has answered, so a slow first load never flashes the "nothing yet" screen at a full inbox.+ // project-wide scope. The state selection does not gate it: counts load for every state the+ // user can see (staff still reach Not actionable when it is the only state with reports), so+ // the verdict stays true whatever states are selected. Hold the list until every count has+ // answered, so a slow first load never flashes the "nothing yet" screen at a full inbox.+ // For the empty-list copy, the state selection only counts as narrowing when the user moved it+ // off the default and it hides at least one state; the default view keeps the scope-aware copy.+ const narrowed =+ hasActiveFilters ||+ (!isDefaultStateFilter(visibleStateFilter) && selectedSections.length < visibleSections.length)const unfilteredView = !hasActiveFilters && scope === INBOX_SCOPE_ENTIRE_PROJECTconst countsSettled = visibleSections.every((key) => sections[key].count !== null)const inboxIsEmpty = unfilteredView && countsSettled && visibleSections.every((key) => sections[key].count === 0)+ const reportsBySection = Object.fromEntries(visibleSections.map((key) => [key, sections[key].reports])) as Record<+ InboxReportSectionKey,+ SignalReport[]+ >+ const rows = mergeReportRows(reportsBySection, selectedSections, sortField, sortDirection)+ useReportImpressions(rows, selectedSections)++ // Rows are fetched once a state is part of the rendered list — a deselected state costs one+ // count request only. `ensureLoaded` no-ops on states that already loaded or are in flight.+ const selectedSectionsKey = selectedSections.join(',')+ useEffect(() => {+ for (const key of selectedSectionsKey.split(',')) {+ if (key) {+ reportListLogic(sectionListLogicProps(key as InboxReportSectionKey)).actions.ensureLoaded()+ }+ }+ }, [selectedSectionsKey])++ const firstLoadPending = selectedSections.some((key) => !sections[key].isLoaded && !sections[key].reportsLoadFailed)+ // Selecting an unloaded state flips `firstLoadPending` back on. Rows already on screen must not+ // be replaced with a skeleton then, so the skeleton only shows before the first settle or when+ // the current selection has no rows to keep visible.+ const settledOnceRef = useRef(false)+ if (!firstLoadPending) {+ settledOnceRef.current = true+ }+ const showFirstLoadSkeleton = firstLoadPending && (!settledOnceRef.current || rows.length === 0)+ const anyLoadFailed = selectedSections.some((key) => sections[key].reportsLoadFailed && !sections[key].isLoaded)+ const pageLoading = selectedSections.some((key) => sections[key].reportsResponseLoading)+ const pageLoadFailed = selectedSections.some((key) => sections[key].pageLoadFailed)+ const hasMore = selectedSections.some((key) => sections[key].hasMore)++ // `ensureLoaded` only fetches a state with nothing loaded and nothing in flight, so retrying+ // after a partial failure refetches the failed states and leaves the loaded ones alone.+ const retryFailedSections = (): void => {+ selectedSections.forEach((key) => reportListLogic(sectionListLogicProps(key)).actions.ensureLoaded())+ }+ // `loadMore` self-guards on `hasMore` and in-flight requests, so this only refetches the pages+ // that actually failed.+ const retryFailedPages = (): void => {+ selectedSections.forEach((key) => {+ if (sections[key].pageLoadFailed) {+ reportListLogic(sectionListLogicProps(key)).actions.loadMore()+ }+ })+ }++ // Read fresh state at intersection time via refs so the observer isn't rebuilt twice per page+ // fetch (`hasMore`/`pageLoading` both flip during a load).+ const hasMoreRef = useRef(hasMore)+ hasMoreRef.current = hasMore+ const loadingRef = useRef(pageLoading)+ loadingRef.current = pageLoading+ const selectedSectionsRef = useRef(selectedSections)+ selectedSectionsRef.current = selectedSections++ // A callback ref, not an effect: the sentinel only enters the DOM once a first page has landed+ // and `hasMore` is true, which is after a mount-only effect has already run and found nothing to+ // observe. Attaching as the node mounts is what keeps paging alive.+ const observerRef = useRef<IntersectionObserver | null>(null)+ const sentinelRef = useCallback((el: HTMLDivElement | null) => {+ observerRef.current?.disconnect()+ observerRef.current = null+ if (!el) {+ return+ }+ const observer = new IntersectionObserver(+ (entries) => {+ if (entries[0]?.isIntersecting && hasMoreRef.current && !loadingRef.current) {+ // `loadMore` self-guards, so only the states that still have pages fetch one.+ // Paging every selected state together keeps the merged order correct: a state+ // whose page is exhausted can't hold rows back while another runs ahead.+ selectedSectionsRef.current.forEach((key) =>+ reportListLogic(sectionListLogicProps(key)).actions.loadMore()+ )+ }+ },+ // Generous prefetch margin so the next page lands well before the user reaches the bottom.+ { rootMargin: '1500px' }+ )+ observer.observe(el)+ observerRef.current = observer+ }, [])+ useEffect(() => () => observerRef.current?.disconnect(), [])+return (<div className="mx-auto flex w-full max-w-4xl flex-col gap-4 px-6 py-3"><div className="flex flex-wrap items-center gap-x-3 gap-y-2">@@ -232,18 +317,78 @@ export function ReportsTab(): JSX.Element {>Triage mode</LemonButton>- <InboxScopeSelect />+ <InboxScopeFilter /></div></div><InboxBulkSelectionBar />{inboxIsEmpty ? (<ReportsEmptyState />+ ) : showFirstLoadSkeleton ? (+ // Hold the rows until every selected state's first page has settled: the states+ // load in parallel, and painting the fastest one first would let the slower ones+ // insert rows among cards already on screen. A state selected later merges its+ // rows in when they land, with the trailing page skeleton covering the wait.+ <CardSkeleton count={4} variant="cards" dashed />+ ) : rows.length === 0 ? (+ anyLoadFailed ? (+ <div className="flex flex-col items-start gap-2 px-1 py-2">+ <p className="m-0 text-sm text-tertiary">Couldn't load these reports.</p>+ <LemonButton+ size="small"+ type="secondary"+ onClick={retryFailedSections}+ data-attr="inbox-report-list-retry"+ >+ Retry+ </LemonButton>+ </div>+ ) : (+ <p className="px-1 py-2 text-sm text-tertiary">{emptyListCopy(scope, narrowed)}</p>+ )) : (- <div className="@container flex flex-col gap-5">- {visibleSections.map((sectionKey) => (- <InboxReportSection key={sectionKey} sectionKey={sectionKey} />+ <div className="@container flex flex-col gap-1.5">+ {rows.map(({ report, sectionKey }) => (+ <ReportCard+ key={report.id}+ report={report}+ sectionKey={sectionKey}+ onRestore={() =>+ reportListLogic(sectionListLogicProps(sectionKey)).actions.restoreReport(report.id)+ }+ />))}+ {/* Skeleton cards continue the list while the next pages load – sleeker than a spinner. */}+ {pageLoading && <CardSkeleton count={2} variant="cards" dashed />}+ {anyLoadFailed && (+ <div className="flex items-center gap-2 px-1 py-2">+ <p className="m-0 text-sm text-tertiary">Couldn't load some of the reports.</p>+ <LemonButton+ size="xsmall"+ type="secondary"+ onClick={retryFailedSections}+ data-attr="inbox-report-list-retry"+ >+ Retry+ </LemonButton>+ </div>+ )}+ {/* A failed next page keeps the loaded rows and the sentinel may sit inside the+ viewport without re-firing, so offer an explicit way to fetch it again. */}+ {!pageLoading && pageLoadFailed && (+ <div className="flex items-center gap-2 px-1 py-2">+ <p className="m-0 text-sm text-tertiary">Couldn't load more reports.</p>+ <LemonButton+ size="xsmall"+ type="secondary"+ onClick={retryFailedPages}+ data-attr="inbox-report-list-retry-page"+ >+ Retry+ </LemonButton>+ </div>+ )}+ {hasMore && <div ref={sentinelRef} className="h-1" aria-hidden />}</div>)}</div>diff --git a/products/signals/frontend/inbox/components/useReportImpressions.ts b/products/signals/frontend/inbox/components/useReportImpressions.tsindex 73b0ca4c762b..b62320c963ec 100644--- a/products/signals/frontend/inbox/components/useReportImpressions.ts+++ b/products/signals/frontend/inbox/components/useReportImpressions.ts@@ -3,16 +3,45 @@ import { useEffect, useRef } from 'react'import { captureInboxReportsImpressed } from '../inboxAnalytics'import { inboxSceneLogic } from '../inboxSceneLogic'-import { reportListLogic } from '../logics/reportListLogic'+import { reportListLogic, sectionListLogicProps } from '../logics/reportListLogic'import { InboxReportSectionKey } from '../types'+import type { MergedReportRow } from '../utils/flatReportList'++interface SectionImpressionState {+ isLoaded: boolean+ reportsLoadFailed: boolean+ reportsResponseLoading: boolean+ totalCount: number | null+ loadedQueryKey: string | null+ loadedContext: { scope: string; hasActiveFilters: boolean } | null+}++function useSectionImpressionState(sectionKey: InboxReportSectionKey): SectionImpressionState {+ const { isLoaded, reportsLoadFailed, reportsResponseLoading, totalCount, loadedQueryKey, loadedContext } =+ useValues(reportListLogic(sectionListLogicProps(sectionKey)))+ return { isLoaded, reportsLoadFailed, reportsResponseLoading, totalCount, loadedQueryKey, loadedContext }+}/**- * Impression log for ranking-model training: record each report the first time it is actually on- * screen in this section, with its rank at that moment. A collapsed section impresses nothing.- * Deduped per section mount so re-renders and detail-pane round-trips don't refire.+ * Impression log for ranking-model training: record each rendered report the first time it is+ * actually on screen in the flat list, with its rank there at that moment. One hook for the whole+ * list, with one dedupe set, so a report matching two states' filters is recorded once however the+ * state requests interleave. Impressions wait until every selected state's request has settled, so+ * the recorded ranks are the merged order the user actually sees, not a fast state's provisional+ * one. The context key covers the state selection and each selected state's loaded query, so+ * narrowing the state filter or changing any server filter re-impresses the rows at their new+ * ranks; loading a further page keeps the context and impresses only the new rows.*/-export function useReportImpressions(sectionKey: InboxReportSectionKey, isOpen: boolean): void {- const { visibleReports, totalCount, isLoaded, loadedQueryKey, loadedContext } = useValues(reportListLogic)+export function useReportImpressions(rows: MergedReportRow[], selectedSections: InboxReportSectionKey[]): void {+ // Fixed-order reads over every state (not just the selected ones), so the hook order never+ // changes when the filter does; the effect below only consults the selected states.+ const sections: Record<InboxReportSectionKey, SectionImpressionState> = {+ monitoring: useSectionImpressionState('monitoring'),+ 'needs-decision': useSectionImpressionState('needs-decision'),+ resolved: useSectionImpressionState('resolved'),+ dismissed: useSectionImpressionState('dismissed'),+ 'not-actionable': useSectionImpressionState('not-actionable'),+ }// The list stays mounted (hidden) while a report/scout detail is open, so gate impressions on the// list actually being the visible surface.const { selectedReportId, selectedScoutSkillName, isScratchpadOpen, isFindingsOpen, isRunsOpen, isTriageOpen } =@@ -25,46 +54,56 @@ export function useReportImpressions(sectionKey: InboxReportSectionKey, isOpen:!isRunsOpen &&!isTriageOpen+ // Settled: every selected state answered (rows landed, or the request failed) with nothing in+ // flight, so the merged rows are stable until the user or a pager changes the query.+ const settled = selectedSections.every(+ (key) => (sections[key].isLoaded || sections[key].reportsLoadFailed) && !sections[key].reportsResponseLoading+ )+ const contextKey = JSON.stringify(selectedSections.map((key) => [key, sections[key].loadedQueryKey]))+const impressedIdsRef = useRef(new Set<string>())- // Dedupe is per query: a sort/search/filter/scope change is a new ranking context, so a report- // re-shown under the new query must impress again (at its new rank) for its later open/action- // events to have a matching impression.- const impressionQueryKeyRef = useRef('')+ const impressionContextKeyRef = useRef('')useEffect(() => {- // totalCount, loadedQueryKey, and loadedContext come from the same response as the rows (not- // the live filter state or the separately-loaded header count), so impressions can't be- // stamped with a stale total or with scope/filter context the user switched to after the- // request went out, and rows from the previous query are never attributed to the new one- // while its refetch is still in flight.- if (- !isOpen ||- !listVisible ||- !isLoaded ||- totalCount === null ||- loadedQueryKey === null ||- loadedContext === null- ) {+ if (!listVisible || !settled) {return}- if (loadedQueryKey !== impressionQueryKeyRef.current) {- impressionQueryKeyRef.current = loadedQueryKey+ // Track the context even when it matches nothing, so coming back to an earlier query is a+ // fresh ranking context and its rows impress again.+ if (contextKey !== impressionContextKeyRef.current) {+ impressionContextKeyRef.current = contextKeyimpressedIdsRef.current = new Set<string>()}- const fresh = visibleReports- .map((report, index) => ({ report, rank: index + 1 }))+ if (rows.length === 0) {+ return+ }+ const fresh = rows+ .map((row, index) => ({ ...row, rank: index + 1 })).filter(({ report }) => !impressedIdsRef.current.has(report.id))if (fresh.length === 0) {return}fresh.forEach(({ report }) => impressedIdsRef.current.add(report.id))- captureInboxReportsImpressed({- tab: sectionKey,- reports: fresh.map(({ report }) => report),- ranks: fresh.map(({ rank }) => rank),- listSize: visibleReports.length,- totalCount,- hasActiveFilters: loadedContext.hasActiveFilters,- scope: loadedContext.scope,- })- }, [isOpen, listVisible, isLoaded, totalCount, visibleReports, sectionKey, loadedQueryKey, loadedContext])+ // One event per contributing state: `tab` and `totalCount` describe the state's own query,+ // while ranks and list size describe the merged list the rows actually rendered in.+ const sectionKeys = [...new Set(fresh.map(({ sectionKey }) => sectionKey))]+ for (const sectionKey of sectionKeys) {+ const context = sections[sectionKey].loadedContext+ if (!context) {+ continue+ }+ const sectionRows = fresh.filter((row) => row.sectionKey === sectionKey)+ captureInboxReportsImpressed({+ tab: sectionKey,+ reports: sectionRows.map(({ report }) => report),+ ranks: sectionRows.map(({ rank }) => rank),+ listSize: rows.length,+ totalCount: sections[sectionKey].totalCount,+ hasActiveFilters: context.hasActiveFilters,+ scope: context.scope,+ })+ }+ // `sections` is a fresh object each render; `contextKey` and `settled` already change with+ // every value the capture reads from it.+ // oxlint-disable-next-line react-hooks/exhaustive-deps+ }, [listVisible, settled, contextKey, rows])}diff --git a/products/signals/frontend/inbox/inboxAnalytics.test.ts b/products/signals/frontend/inbox/inboxAnalytics.test.tsindex 1e74fa805cb7..06af1d7ee407 100644--- a/products/signals/frontend/inbox/inboxAnalytics.test.ts+++ b/products/signals/frontend/inbox/inboxAnalytics.test.ts@@ -211,6 +211,7 @@ describe('inboxAnalytics', () => {sourceProductFilter: ['error_tracking'],scoutFilter: [],priorityFilter: ['P0'],+ stateFilter: ['monitoring'],searchQuery: ' acme checkout crash ',hasActiveFilters: true,})diff --git a/products/signals/frontend/inbox/inboxAnalytics.ts b/products/signals/frontend/inbox/inboxAnalytics.tsindex e657d631dc75..685e34243162 100644--- a/products/signals/frontend/inbox/inboxAnalytics.ts+++ b/products/signals/frontend/inbox/inboxAnalytics.ts@@ -30,7 +30,6 @@ export const INBOX_EVENTS = {QUERY_CHANGED: 'Inbox query changed',REPORTS_IMPRESSED: 'Inbox reports impressed',REPORT_OPENED: 'Inbox report opened',- SECTION_TOGGLED: 'Inbox section toggled',REPORT_CLOSED: 'Inbox report closed',REPORT_SCROLLED: 'Inbox report scrolled',REPORT_ACTION: 'Inbox report action',@@ -131,7 +130,16 @@ export type InboxReportActionOutcome = 'success' | 'failure' | 'blocked' | 'limiexport type InboxPanelName = 'runs' | 'config' | 'scratchpad' | 'findings' | 'triage'/** Which control moved the report list to a new query. `url` is a shared/deep link being applied. */-export type InboxQueryChange = 'scope' | 'sort' | 'source_product' | 'scout' | 'priority' | 'search' | 'clear' | 'url'+export type InboxQueryChange =+ | 'scope'+ | 'sort'+ | 'source_product'+ | 'scout'+ | 'priority'+ | 'state'+ | 'search'+ | 'clear'+ | 'url'/** Surface a scout-management event fired from. Matches the desktop values. */export type ScoutSurface = 'fleet_list' | 'scout_detail' | 'empty_state' | 'replay_vision_scanner'@@ -287,6 +295,8 @@ export function captureInboxViewed(params: {hasActiveFilters: booleansourceProductFilter: string[]priorityFilter: string[]+ /** Selected report states on the flat Reports list; [] (every state) on other surfaces. */+ stateFilter?: string[]scope: string}): void {captureInboxEvent(INBOX_EVENTS.VIEWED, {@@ -299,6 +309,7 @@ export function captureInboxViewed(params: {has_active_filters: params.hasActiveFilters,source_product_filter: params.sourceProductFilter,priority_filter: params.priorityFilter,+ state_filter: params.stateFilter ?? [],scope: params.scope,...priorityBreakdown(params.reports),...actionabilityBreakdown(params.reports),@@ -367,18 +378,6 @@ export function captureInboxReportOpened(params: {})}-/**- * A Reports list section was expanded or collapsed. Resolved and Not actionable start collapsed,- * so without this a reader who scrolls down to the resolved work is invisible until a card in it- * impresses. Cloud-only: the desktop app has no collapsible sections.- */-export function captureInboxSectionToggled(params: { section: InboxReportSectionKey; isOpen: boolean }): void {- captureInboxEvent(INBOX_EVENTS.SECTION_TOGGLED, {- section: params.section,- is_open: params.isOpen,- })-}-export function captureInboxReportClosed(params: {report: SignalReport@@ -587,6 +586,7 @@ export function captureInboxQueryChanged(params: {sourceProductFilter: string[]scoutFilter: string[]priorityFilter: string[]+ stateFilter: string[]searchQuery: stringhasActiveFilters: boolean}): void {@@ -600,6 +600,7 @@ export function captureInboxQueryChanged(params: {source_product_filter: params.sourceProductFilter,scout_filter: params.scoutFilter,priority_filter: params.priorityFilter,+ state_filter: params.stateFilter,has_search: search.length > 0,search_length: search.length,has_active_filters: params.hasActiveFilters,diff --git a/products/signals/frontend/inbox/inboxSceneLogic.ts b/products/signals/frontend/inbox/inboxSceneLogic.tsindex ab14a4df9d5a..781073dc7b71 100644--- a/products/signals/frontend/inbox/inboxSceneLogic.ts+++ b/products/signals/frontend/inbox/inboxSceneLogic.ts@@ -38,6 +38,7 @@ import { scratchpadLogic } from './logics/scratchpadLogic'import { signalSourcesLogic } from './signalSourcesLogic'import {INBOX_LEGACY_TAB_KEYS,+ INBOX_REPORT_SECTION_KEYS,INBOX_STAFF_ONLY_TAB_KEYS,INBOX_TAB_KEYS,InboxReportSectionKey,@@ -47,6 +48,7 @@ import {SignalScoutRunStatus,SignalScoutRunSummary,} from './types'+import { mergeReportRows, selectedFlatListSections } from './utils/flatReportList'import { isInboxRedesignEnabled } from './utils/inboxRedesign'import { inboxTabRedirectPath } from './utils/inboxReportUrls'import { decodeScoutCreateTemplate } from './utils/scoutTemplateDeepLink'@@ -174,14 +176,48 @@ function findLoadedReport(id: string): SignalReport | null {}/**- * Position (1-based) and size of the report's list, for `Inbox report opened`. Searches the mounted- * per-section lists for the report. Null when the report isn't in a loaded list (e.g. a cold deep-link).+ * Position (1-based) and size of the report's list, for `Inbox report opened` and `Inbox report+ * scrolled`. Under the flat Reports list (`flatList`) the rank is rebuilt with the same selection,+ * dedupe, and ordering the list rendered with, so these outcome events join to the impressions+ * recorded at the same rank. With the redesign flag off each tab is its own list, so the rank is+ * the position within the report's own state. Null when the report isn't in a rendered list (e.g.+ * a cold deep-link).*/-function findReportRank(id: string): {+function findReportRank(+ id: string,+ flatList: boolean+): {rank: number | nulllistSize: number | nullsection: InboxReportSectionKey | null} {+ if (flatList) {+ const filterValues = inboxFiltersLogic.findMounted()?.values+ if (!filterValues) {+ return { rank: null, listSize: null, section: null }+ }+ const isStaff = userLogic.findMounted()?.values.user?.is_staff ?? false+ const reportsBySection = Object.fromEntries(+ INBOX_REPORT_SECTION_KEYS.map((sectionKey) => [+ sectionKey,+ reportListLogic.findMounted({+ sectionKey,+ listParams: INBOX_REPORT_SECTION_LIST_PARAMS[sectionKey],+ })?.values.reports ?? [],+ ])+ ) as Record<InboxReportSectionKey, SignalReport[]>+ const rows = mergeReportRows(+ reportsBySection,+ selectedFlatListSections(filterValues.visibleStateFilter, isStaff),+ filterValues.sortField,+ filterValues.sortDirection+ )+ const idx = rows.findIndex((row) => row.report.id === id)+ if (idx >= 0) {+ return { rank: idx + 1, listSize: rows.length, section: rows[idx].sectionKey }+ }+ return { rank: null, listSize: null, section: null }+ }for (const sectionKey of Object.keys(INBOX_REPORT_SECTION_LIST_PARAMS) as InboxReportSectionKey[]) {const mounted = reportListLogic.findMounted({sectionKey,@@ -794,7 +830,7 @@ export const inboxSceneLogic = kea<inboxSceneLogicType>([if (!report || values.selectedReportId !== report.id || cache.openTracking?.report.id === report.id) {return}- const { rank, listSize, section } = findReportRank(report.id)+ const { rank, listSize, section } = findReportRank(report.id, values.isRedesign)captureInboxReportOpened({report,openMethod: (cache.pendingOpenMethod as InboxReportOpenMethod | undefined) ?? 'unknown',@@ -818,7 +854,7 @@ export const inboxSceneLogic = kea<inboxSceneLogicType>([return}open.scrolled = true- const { rank, listSize } = findReportRank(open.report.id)+ const { rank, listSize } = findReportRank(open.report.id, values.isRedesign)captureInboxReportScrolled({report: open.report,rank,diff --git a/products/signals/frontend/inbox/logics/inboxFiltersLogic.test.ts b/products/signals/frontend/inbox/logics/inboxFiltersLogic.test.tsindex 1051f8ddd455..05980edc66f5 100644--- a/products/signals/frontend/inbox/logics/inboxFiltersLogic.test.ts+++ b/products/signals/frontend/inbox/logics/inboxFiltersLogic.test.ts@@ -1,7 +1,12 @@/* 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'import posthog from 'posthog-js'+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { urls } from 'scenes/urls'+import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'@@ -21,6 +26,7 @@ const DEFAULT_STATE: InboxFilterState = {sourceProductFilter: [],scoutFilter: [],priorityFilter: [],+ stateFilter: ['monitoring', 'needs-decision'],sortField: 'priority',sortDirection: 'asc',searchQuery: '',@@ -54,7 +60,7 @@ describe('inboxFiltersLogic', () => {it.each<[string, InboxFilterState, Record<string, string>]>([[- 'scope + sources + scouts + priorities + custom sort + search',+ 'scope + sources + scouts + priorities + states + custom sort + search',{scope: 'entire-project',sourceProductFilter: ['error_tracking', 'github'],@@ -62,6 +68,7 @@ describe('inboxFiltersLogic', () => {// static valid-set check — unlike sources.scoutFilter: ['signals-scout-error-tracking', 'my-custom-scout'],priorityFilter: ['P0', 'P2'],+ stateFilter: ['monitoring', 'resolved'],sortField: 'created_at',sortDirection: 'desc',searchQuery: 'checkout crash',@@ -71,6 +78,7 @@ describe('inboxFiltersLogic', () => {source: 'error_tracking,github',scout: 'signals-scout-error-tracking,my-custom-scout',priority: 'P0,P2',+ state: 'monitoring,resolved',sort: 'created_at:desc',search: 'checkout crash',},@@ -80,6 +88,9 @@ describe('inboxFiltersLogic', () => {{ ...DEFAULT_STATE, scope: 'teammate:0199ed4a-5c03-0000-3220-df21df612e95' },{ scope: 'teammate:0199ed4a-5c03-0000-3220-df21df612e95' },],+ // 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' }],])('round-trips %s through encode/decode', (_name, state, expectedParams) => {expect(filterSearchParams(state)).toEqual(expectedParams)expect(parseFilterSearchParams(expectedParams)).toEqual(state)@@ -88,12 +99,13 @@ describe('inboxFiltersLogic', () => {// A shared link is authoritative but untrusted: unknown values (a malformed teammate id, which would// otherwise reach the report-list API as a bad reviewer UUID, and a syntactically valid but// unsupported sort combination the Sort control can't display) must not leak into filter state.- it('drops unknown sources, priorities, malformed teammate scope and unsupported sort', () => {+ it('drops unknown sources, priorities, states, malformed teammate scope and unsupported sort', () => {expect(parseFilterSearchParams({scope: 'teammate:not-a-uuid',source: 'error_tracking,bogus_source',priority: 'P9,P1',+ state: 'monitoring,bogus-state',// priority:desc has a valid field and direction but is not one of the offered sort options.sort: 'priority:desc',})@@ -101,6 +113,7 @@ describe('inboxFiltersLogic', () => {...DEFAULT_STATE,sourceProductFilter: ['error_tracking'],priorityFilter: ['P1'],+ stateFilter: ['monitoring'],})})})@@ -152,6 +165,18 @@ describe('inboxFiltersLogic', () => {expect.objectContaining({ change: 'search', has_search: true, search_length: 8 }),])})++ // The flat Reports list has no `?view=` sub-view, so a query change on it must attribute to+ // the `reports` tab and agree with the `tab` that `Inbox viewed` sends for the same visit.+ it('attributes a redesigned Reports query change to the reports tab', async () => {+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.INBOX_REDESIGN], {+ [FEATURE_FLAGS.INBOX_REDESIGN]: true,+ })+ router.actions.push(urls.inbox('reports'))+ logic.actions.toggleState('needs-decision')+ await expectLogic(logic).toFinishAllListeners()+ expect(queryChanges()).toEqual([expect.objectContaining({ change: 'state', tab: 'reports' })])+ })})describe('scout filters', () => {diff --git a/products/signals/frontend/inbox/logics/inboxFiltersLogic.ts b/products/signals/frontend/inbox/logics/inboxFiltersLogic.tsindex eec0dba24db2..1394a72d3298 100644--- a/products/signals/frontend/inbox/logics/inboxFiltersLogic.ts+++ b/products/signals/frontend/inbox/logics/inboxFiltersLogic.ts@@ -7,15 +7,19 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'import { isUUIDLike } from 'lib/utils/guards'import { urls } from 'scenes/urls'+import { userLogic } from 'scenes/userLogic'++import type { UserType } from '~/types'import { INBOX_PRIORITY_OPTIONS, INBOX_SORT_OPTIONS, INBOX_SOURCE_OPTIONS } from '../filterOptions'import { captureInboxQueryChanged, InboxQueryChange } from '../inboxAnalytics'import {INBOX_LEGACY_TAB_KEYS,- INBOX_PRIMARY_REPORT_SECTION_KEY,INBOX_REPORT_SECTION_KEYS,INBOX_SCOPE_FOR_YOU,+ INBOX_STAFF_ONLY_REPORT_SECTION_KEYS,INBOX_TAB_KEYS,+ InboxReportSectionKey,InboxScope,SignalReportPriority,} from '../types'@@ -34,11 +38,30 @@ export type InboxSortDirection = 'asc' | 'desc'const DEFAULT_SORT_FIELD: InboxSortField = 'priority'const DEFAULT_SORT_DIRECTION: InboxSortDirection = 'asc'+/**+ * The states selected by default: the two that hold open work. The closed states (Resolved,+ * Dismissed) stay one checkbox away so the fresh inbox leads with what needs a person.+ */+export const DEFAULT_STATE_FILTER: InboxReportSectionKey[] = ['monitoring', 'needs-decision']++/**+ * URL value for an explicitly empty selection (every state). An absent `state` param means the+ * default selection, so the empty selection needs its own encoding; without it, the URL rewrite+ * after unchecking the last state would immediately hydrate the default back.+ */+const STATE_PARAM_ALL = 'all'++/** Whether a state selection is exactly the default, in any order. */+export function isDefaultStateFilter(stateFilter: InboxReportSectionKey[]): boolean {+ return sameSet(stateFilter, DEFAULT_STATE_FILTER)+}+// Query-param keys that mirror the filter state so a view can be shared via URL.-const FILTER_URL_KEYS = ['scope', 'source', 'scout', 'priority', 'sort', 'search'] as const+const FILTER_URL_KEYS = ['scope', 'source', 'scout', 'priority', 'state', 'sort', 'search'] as constconst VALID_SOURCE_VALUES = new Set(INBOX_SOURCE_OPTIONS.map((o) => o.value))const VALID_PRIORITIES = new Set<string>(INBOX_PRIORITY_OPTIONS)+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}`))@@ -48,6 +71,7 @@ export interface InboxFilterState {sourceProductFilter: string[]scoutFilter: string[]priorityFilter: SignalReportPriority[]+ stateFilter: InboxReportSectionKey[]sortField: InboxSortFieldsortDirection: InboxSortDirectionsearchQuery: string@@ -74,6 +98,18 @@ function parseListParam(raw: unknown, valid: Set<string>): string[] {return raw.split(',').filter((v) => valid.has(v))}+/**+ * Decode the `state` param: the sentinel means every state, an explicit list is validated, and+ * anything else (absent, or nothing but unknown values) falls back to the default selection.+ */+function parseStateParam(raw: unknown): InboxReportSectionKey[] {+ if (raw === STATE_PARAM_ALL) {+ return []+ }+ const parsed = parseListParam(raw, VALID_STATE_VALUES) as InboxReportSectionKey[]+ return parsed.length > 0 ? parsed : DEFAULT_STATE_FILTER+}+// Scout skill names are team-specific and dynamic, so there is no static valid set to check a// shared link against — accept any non-empty comma-separated slugs; an unknown scout simply// matches no reports server-side.@@ -101,6 +137,7 @@ export function parseFilterSearchParams(searchParams: Record<string, any>): InbosourceProductFilter: parseListParam(searchParams.source, VALID_SOURCE_VALUES),scoutFilter: parseScoutParam(searchParams.scout),priorityFilter: parseListParam(searchParams.priority, VALID_PRIORITIES) as SignalReportPriority[],+ stateFilter: parseStateParam(searchParams.state),sortField,sortDirection,searchQuery: typeof searchParams.search === 'string' ? searchParams.search : '',@@ -108,11 +145,12 @@ export function parseFilterSearchParams(searchParams: Record<string, any>): Inbo}/**- * The list the filters apply to, for the `tab` analytics property: the Reports view from the URL's- * `?view=` (the landing view when absent), another page tab's key, or null off a tab route (the- * scout panels, or a bare `/inbox`). With the redesign flag off every tab is its own list, so the- * tab segment is the answer as it stands. Read from the router rather than connected from- * `inboxSceneLogic`, which already connects this logic — the reverse edge would be a cycle.+ * The inbox page tab the filters apply to, for the `tab` analytics property: the tab segment from+ * the URL (`reports`, `scouts`, or `settings` under the redesign, or a legacy tab key), or null off+ * a tab route (the scout panels, or a bare `/inbox`). The redesigned Reports tab is one flat list+ * with no sub-view, so it reports `reports` and stays consistent with the `tab` that+ * `captureInboxViewed` sends for the same visit. Read from the router rather than connected from+ * `inboxSceneLogic`, which already connects this logic, because the reverse edge would be a cycle.*/function currentInboxTab(redesign: boolean): string | null {const segments = router.values.location.pathname.split('/').filter(Boolean)@@ -122,11 +160,7 @@ function currentInboxTab(redesign: boolean): string | null {if (!candidate || !tabKeys.includes(candidate)) {return null}- if (!redesign || candidate !== 'reports') {- return candidate- }- const view = router.values.searchParams.view- return (INBOX_REPORT_SECTION_KEYS as readonly string[]).includes(view) ? view : INBOX_PRIMARY_REPORT_SECTION_KEY+ return candidate}function sameSet(a: string[], b: string[]): boolean {@@ -148,6 +182,11 @@ export function filterSearchParams(values: InboxFilterState): Record<string, strif (values.priorityFilter.length > 0) {params.priority = values.priorityFilter.join(',')}+ if (values.stateFilter.length === 0) {+ params.state = STATE_PARAM_ALL+ } else if (!isDefaultStateFilter(values.stateFilter)) {+ params.state = values.stateFilter.join(',')+ }if (values.sortField !== DEFAULT_SORT_FIELD || values.sortDirection !== DEFAULT_SORT_DIRECTION) {params.sort = `${values.sortField}:${values.sortDirection}`}@@ -196,6 +235,7 @@ export function buildSignalReportListOrdering(field: InboxSortField, direction:// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface inboxFiltersLogicValues {featureFlags: FeatureFlagsSet // featureFlagLogic+ user: UserType | null // userLogicavailableReviewers: InboxReviewerOption[]availableReviewersLoading: booleanhasActiveFilters: boolean@@ -208,6 +248,8 @@ export interface inboxFiltersLogicValues {sortDirection: InboxSortDirectionsortField: InboxSortFieldsourceProductFilter: string[]+ stateFilter: ('dismissed' | 'monitoring' | 'needs-decision' | 'not-actionable' | 'resolved')[]+ visibleStateFilter: InboxReportSectionKey[]}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -281,6 +323,9 @@ export interface inboxFiltersLogicActions {toggleSourceProduct: (source: string) => {source: string}+ toggleState: (state: InboxReportSectionKey) => {+ state: 'dismissed' | 'monitoring' | 'needs-decision' | 'not-actionable' | 'resolved'+ }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -293,6 +338,10 @@ export interface inboxFiltersLogicMeta {priorityFilter: SignalReportPriority[]) => booleanisRedesign: (featureFlags: FeatureFlagsSet) => boolean+ visibleStateFilter: (+ stateFilter: ('dismissed' | 'monitoring' | 'needs-decision' | 'not-actionable' | 'resolved')[],+ user: UserType | null+ ) => InboxReportSectionKey[]}}@@ -322,7 +371,7 @@ export const inboxFiltersLogic = kea<inboxFiltersLogicType>([path(['scenes', 'inbox', 'logics', 'inboxFiltersLogic']),connect(() => ({- values: [featureFlagLogic, ['featureFlags']],+ values: [featureFlagLogic, ['featureFlags'], userLogic, ['user']],})),actions({@@ -336,6 +385,10 @@ export const inboxFiltersLogic = kea<inboxFiltersLogicType>([toggleScout: (scout: string) => ({ scout }),clearScoutFilter: true,togglePriority: (priority: SignalReportPriority) => ({ priority }),+ // The report states (Needs decision, Review and merge, …) shown in the flat Reports list.+ // Multi-select: the open-work states are selected by default (DEFAULT_STATE_FILTER), and an+ // empty selection means every state the user can see.+ toggleState: (state: InboxReportSectionKey) => ({ state }),// Replace the whole selection. The priority control is a single select, but the state// stays a list so a shared link carrying several priorities still filters by all of them.setPriorityFilter: (priorities: SignalReportPriority[]) => ({ priorities }),@@ -353,9 +406,13 @@ export const inboxFiltersLogic = kea<inboxFiltersLogicType>([availableReviewers: [[] as InboxReviewerOption[],{- loadAvailableReviewers: async ({ query }: { query?: string } = {}) => {+ loadAvailableReviewers: async ({ query }: { query?: string } = {}, breakpoint) => {// The api wrapper already returns the typed `{ user_uuid, name, email }[]` array.- return await api.signalReports.availableReviewers(query)+ const reviewers = await api.signalReports.availableReviewers(query)+ // Discard this result if a newer search superseded it while the request was in+ // flight, so a slower earlier response cannot overwrite the newer rows.+ breakpoint()+ return reviewers},},],@@ -373,6 +430,7 @@ export const inboxFiltersLogic = kea<inboxFiltersLogicType>([sourceProductFilter: values.sourceProductFilter,scoutFilter: values.scoutFilter,priorityFilter: values.priorityFilter,+ stateFilter: values.stateFilter,searchQuery: values.searchQuery,hasActiveFilters: values.hasActiveFilters,})@@ -391,6 +449,7 @@ export const inboxFiltersLogic = kea<inboxFiltersLogicType>([clearScoutFilter: () => captureQueryChange('scout'),togglePriority: () => captureQueryChange('priority'),setPriorityFilter: () => captureQueryChange('priority'),+ toggleState: () => captureQueryChange('state'),clearFilters: () => captureQueryChange('clear'),setFilters: () => captureQueryChange('url'),// The search box fires per keystroke; settle first so a typed phrase is one event.@@ -482,11 +541,24 @@ export const inboxFiltersLogic = kea<inboxFiltersLogicType>([clearFilters: () => [],},],+ stateFilter: [+ DEFAULT_STATE_FILTER,+ { persist: true },+ {+ toggleState: (current, { state }) =>+ current.includes(state) ? current.filter((s) => s !== state) : [...current, state],+ setFilters: (_, { filters }) => filters.stateFilter,+ clearFilters: () => DEFAULT_STATE_FILTER,+ },+ ],}),selectors({- // Whether any 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 untouched.+ // 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+ // 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],(@@ -504,6 +576,18 @@ export const inboxFiltersLogic = kea<inboxFiltersLogicType>([(s) => [s.featureFlags],(featureFlags: FeatureFlagsSet): boolean => isInboxRedesignEnabled(featureFlags),],+ // The stored state filter can name states the current user cannot see: a staff-only state+ // from a shared link, or one persisted before staff access changed. The list and the filter+ // control read this narrowed view, so a hidden state can never strand the list on a+ // selection the control has no checkbox to clear. The raw `stateFilter` stays stored and in+ // the URL, so a staff user opening the same link still gets the full selection.+ visibleStateFilter: [+ (s) => [s.stateFilter, s.user],+ (stateFilter: InboxReportSectionKey[], user: UserType | null): InboxReportSectionKey[] =>+ user?.is_staff+ ? stateFilter+ : stateFilter.filter((key) => !INBOX_STAFF_ONLY_REPORT_SECTION_KEYS.includes(key)),+ ],}),actionToUrl(({ values }) => {@@ -520,6 +604,7 @@ export const inboxFiltersLogic = kea<inboxFiltersLogicType>([clearScoutFilter: toUrl,togglePriority: toUrl,setPriorityFilter: toUrl,+ toggleState: toUrl,setSearchQuery: toUrl,clearFilters: toUrl,}@@ -551,6 +636,7 @@ export const inboxFiltersLogic = kea<inboxFiltersLogicType>([!sameSet(values.sourceProductFilter, parsed.sourceProductFilter) ||!sameSet(values.scoutFilter, parsed.scoutFilter) ||!sameSet(values.priorityFilter, parsed.priorityFilter) ||+ !sameSet(values.stateFilter, parsed.stateFilter) ||values.sortField !== parsed.sortField ||values.sortDirection !== parsed.sortDirection ||values.searchQuery !== parsed.searchQuerydiff --git a/products/signals/frontend/inbox/logics/inboxReportSectionsLogic.ts b/products/signals/frontend/inbox/logics/inboxReportSectionsLogic.tsdeleted file mode 100644index cb048338bbf8..000000000000--- a/products/signals/frontend/inbox/logics/inboxReportSectionsLogic.ts+++ /dev/null@@ -1,93 +0,0 @@-import { MakeLogicType, actions, kea, listeners, path, reducers, selectors } from 'kea'--import { captureInboxSectionToggled } from '../inboxAnalytics'-import { INBOX_REPORT_SECTION_KEYS, InboxReportSectionKey } from '../types'--/** localStorage key for the per-user collapsed/expanded sections (see `sectionOverrides`). */-export const INBOX_OPEN_SECTIONS_STORAGE_KEY = 'inbox-open-report-sections'--/**- * How a section starts before the user has collapsed or expanded it. The two sections that carry- * work to do open; the three that are a record of work already judged stay out of the way.- */-export const DEFAULT_OPEN_SECTIONS: Record<InboxReportSectionKey, boolean> = {- monitoring: true,- 'needs-decision': true,- resolved: false,- dismissed: false,- 'not-actionable': false,-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface inboxReportSectionsLogicValues {- openSections: Record<InboxReportSectionKey, boolean>- sectionOverrides: Record<string, boolean>-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface inboxReportSectionsLogicActions {- toggleSection: (section: InboxReportSectionKey) => {- section: 'dismissed' | 'monitoring' | 'needs-decision' | 'not-actionable' | 'resolved'- }-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface inboxReportSectionsLogicMeta {- __keaTypeGenInternalSelectorTypes: {- openSections: (sectionOverrides: Record<string, boolean>) => Record<InboxReportSectionKey, boolean>- }-}--export type inboxReportSectionsLogicType = MakeLogicType<- inboxReportSectionsLogicValues,- inboxReportSectionsLogicActions,- Record<string, any>,- inboxReportSectionsLogicMeta->--/**- * Which Reports sections are expanded. Persisted, so a user who collapses Monitoring finds it- * collapsed on their next visit.- *- * Only sections the user has actually toggled are stored. Everything else reads through to- * `DEFAULT_OPEN_SECTIONS`, so a changed default reaches every user who never expressed a- * preference, and a section added later starts at its own default rather than at `false`.- */-export const inboxReportSectionsLogic = kea<inboxReportSectionsLogicType>([- path(['scenes', 'inbox', 'logics', 'inboxReportSectionsLogic']),-- actions({- toggleSection: (section: InboxReportSectionKey) => ({ section }),- }),-- reducers({- sectionOverrides: [- {} as Record<string, boolean>,- { persist: true, storageKey: INBOX_OPEN_SECTIONS_STORAGE_KEY },- {- toggleSection: (state, { section }) => ({- ...state,- [section]: !(state[section] ?? DEFAULT_OPEN_SECTIONS[section]),- }),- },- ],- }),-- listeners(({ values }) => ({- // Listeners run after reducers, so `openSections` already holds the new state.- toggleSection: ({ section }) => captureInboxSectionToggled({ section, isOpen: values.openSections[section] }),- })),-- selectors({- openSections: [- (s) => [s.sectionOverrides],- (sectionOverrides: Record<string, boolean>): Record<InboxReportSectionKey, boolean> =>- Object.fromEntries(- INBOX_REPORT_SECTION_KEYS.map((section) => [- section,- sectionOverrides[section] ?? DEFAULT_OPEN_SECTIONS[section],- ])- ) as Record<InboxReportSectionKey, boolean>,- ],- }),-])diff --git a/products/signals/frontend/inbox/logics/inboxTriageLogic.ts b/products/signals/frontend/inbox/logics/inboxTriageLogic.tsindex 2f9fd93ce033..bb085a87a825 100644--- a/products/signals/frontend/inbox/logics/inboxTriageLogic.ts+++ b/products/signals/frontend/inbox/logics/inboxTriageLogic.ts@@ -394,7 +394,7 @@ export const inboxTriageLogic = kea<inboxTriageLogicType>([if (!report) {return}- // Triage walks Needs a PR, so no report here has an open PR to close.+ // Triage walks Needs decision, so no report here has an open PR to close.openResolveReportDialog({reportTitle: displayConventionalCommitTitle(report.title, 'Untitled report'),hotkeys: true,diff --git a/products/signals/frontend/inbox/logics/reportListLogic.test.ts b/products/signals/frontend/inbox/logics/reportListLogic.test.tsindex 293f2ac343e9..a1179650b5cd 100644--- a/products/signals/frontend/inbox/logics/reportListLogic.test.ts+++ b/products/signals/frontend/inbox/logics/reportListLogic.test.ts@@ -12,12 +12,7 @@ import {SignalReport,SignalReportStatus,} from '../types'-import {- INBOX_REPORT_SECTION_LIST_PARAMS,- reportListLogic,- SECTION_PAGE_SIZE,- shouldDefaultToEntireProject,-} from './reportListLogic'+import { INBOX_REPORT_SECTION_LIST_PARAMS, reportListLogic, shouldDefaultToEntireProject } from './reportListLogic'const REPORTS_URL = '/api/projects/:team_id/signals/reports/'@@ -66,7 +61,7 @@ describe('reportListLogic', () => {['user has assigned reports', { count: 3 }],// The user deliberately picked a scope – never override it, even with zero reports.['user chose their scope', { hasUserChosenScope: true }],- // Only the primary section (Needs a PR) drives the default.+ // Only the primary section (Needs decision) drives the default.['not the primary section', { sectionKey: 'monitoring' as InboxReportSectionKey }],// Already off For you – nothing to default.['already entire project', { scope: INBOX_SCOPE_ENTIRE_PROJECT as InboxScope }],@@ -79,12 +74,10 @@ describe('reportListLogic', () => {})})- // A section shows a short window over a much larger server page, so "Show more" has two jobs- // that are easy to get wrong in opposite directions: widening the window, and reaching for the- // next server page only once the window has outrun the rows already in hand.- describe('section paging window', () => {- // Two full sections' worth on the first page, so the first press is served from memory.- const FIRST_PAGE = Array.from({ length: SECTION_PAGE_SIZE * 2 }, (_, i) => makeReport(`page-1-${i}`))+ // The flat list pages every state through `loadMore`, so it must append from the loaded offset+ // and stay quiet once the server says there is nothing further.+ describe('list paging', () => {+ const FIRST_PAGE = Array.from({ length: 10 }, (_, i) => makeReport(`page-1-${i}`))const SECOND_PAGE = [makeReport('page-2-0')]let requestedOffsets: (string | null)[]let logic: ReturnType<typeof reportListLogic.build>@@ -128,64 +121,65 @@ describe('reportListLogic', () => {afterEach(() => logic.unmount())- it('shows one section-worth of the loaded page', () => {- expect(logic.values.visibleReports).toHaveLength(SECTION_PAGE_SIZE)- expect(logic.values.hiddenReportCount).toBe(FIRST_PAGE.length + SECOND_PAGE.length - SECTION_PAGE_SIZE)- })-- it('widens the window from rows already loaded, without a new request', async () => {- logic.actions.showMore()+ it('appends the next server page from the loaded offset, then stops', async () => {+ logic.actions.loadMore()await expectLogic(logic).toFinishAllListeners()- expect(logic.values.visibleReports).toHaveLength(SECTION_PAGE_SIZE * 2)- expect(requestedOffsets).toEqual(['0'])- })+ expect(requestedOffsets).toEqual(['0', String(FIRST_PAGE.length)])+ expect(logic.values.reports).toHaveLength(FIRST_PAGE.length + SECOND_PAGE.length)- it('fetches the next page once the window outruns the loaded rows', async () => {- logic.actions.showMore()+ // The second page came back with `next: null`, so a further loadMore fires no request.+ logic.actions.loadMore()await expectLogic(logic).toFinishAllListeners()- logic.actions.showMore()- await expectLogic(logic).toFinishAllListeners()-expect(requestedOffsets).toEqual(['0', String(FIRST_PAGE.length)])- expect(logic.values.reports).toHaveLength(FIRST_PAGE.length + SECOND_PAGE.length)})- // "Show more" widens the window past the loaded rows before the next page lands, so a failed- // next-page request leaves the window ahead of the loaded rows. The hidden count must track- // the rows on screen, not the window size — otherwise it hits zero and unmounts the only- // control that can retry, stranding the unfetched rows.- it('keeps Show more after a failed next-page request so the rows stay reachable', async () => {+ // A failed next page keeps the loaded rows and `hasMore`, and the scroll sentinel may sit+ // inside the viewport without re-firing. The flag is what surfaces the retry control, and a+ // plain `loadMore` must be able to fetch the page again.+ it('flags a failed next page and clears the flag on a successful retry', async () => {+ let failNextPage = trueuseMocks({get: {[REPORTS_URL]: ({ request }) => {const offset = new URL(request.url).searchParams.get('offset')- return offset && offset !== '0'- ? [500, {}]- : [- 200,- {- count: FIRST_PAGE.length + SECOND_PAGE.length,- next: 'http://localhost/api/projects/997/signals/reports/?offset=50',- previous: null,- results: FIRST_PAGE,- },- ]+ if (offset && offset !== '0') {+ if (failNextPage) {+ failNextPage = false+ return [500, {}]+ }+ return [+ 200,+ {+ count: FIRST_PAGE.length + SECOND_PAGE.length,+ next: null,+ previous: null,+ results: SECOND_PAGE,+ },+ ]+ }+ return [+ 200,+ {+ count: FIRST_PAGE.length + SECOND_PAGE.length,+ next: 'http://localhost/api/projects/997/signals/reports/?offset=50',+ previous: null,+ results: FIRST_PAGE,+ },+ ]},},})- // First press is served from memory; the second outruns the loaded rows and the- // next-page fetch fails.- logic.actions.showMore()- await expectLogic(logic).toFinishAllListeners()- logic.actions.showMore()- await expectLogic(logic).toFinishAllListeners()- // The second page never arrived, so the loaded rows are unchanged...+ logic.actions.loadMore()+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.pageLoadFailed).toBe(true)expect(logic.values.reports).toHaveLength(FIRST_PAGE.length)- expect(logic.values.visibleReports).toHaveLength(FIRST_PAGE.length)- // ...but the section still knows one report is held back and offers to fetch it again.- expect(logic.values.hiddenReportCount).toBe(SECOND_PAGE.length)++ logic.actions.loadMore()+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.pageLoadFailed).toBe(false)+ expect(logic.values.reports).toHaveLength(FIRST_PAGE.length + SECOND_PAGE.length)})})})diff --git a/products/signals/frontend/inbox/logics/reportListLogic.ts b/products/signals/frontend/inbox/logics/reportListLogic.tsindex 88c69bbffb55..99e9455347eb 100644--- a/products/signals/frontend/inbox/logics/reportListLogic.ts+++ b/products/signals/frontend/inbox/logics/reportListLogic.ts@@ -32,15 +32,6 @@ import type { InboxFilterState, InboxSortDirection, InboxSortField } from './inbconst PAGE_SIZE = 50-/**- * How many rows a section shows before "Show more". Sections stack in one column, so each one has- * to stay short enough that the sections below it are still reachable without scrolling past a- * whole list. Well under the server `PAGE_SIZE`, so the first few "Show more" presses are free.- */-// Annotated rather than inferred: kea-typegen reads a bare `= 5` as the literal type `5` and-// types the reducer it defaults as `5`, which then rejects the widened value.-export const SECTION_PAGE_SIZE: number = 5-/** Fixed, section-defining server filter (e.g. `{ has_implementation_pr: 'true' }`). */export type ReportListParams = Record<string, string>@@ -76,6 +67,11 @@ export const INBOX_REPORT_SECTION_LIST_PARAMS: Record<InboxReportSectionKey, Rep'not-actionable': { actionability: 'not_actionable' },}+/** Logic props for one report state's keyed instance, shared by the flat Reports list consumers. */+export function sectionListLogicProps(sectionKey: InboxReportSectionKey): ReportListLogicProps {+ return { sectionKey, listParams: INBOX_REPORT_SECTION_LIST_PARAMS[sectionKey] }+}+/*** The keyed list instance behind a legacy tab (redesign flag off). Every tab shows one section with* that section's filter, except Archive, which lists resolved and dismissed reports together. It@@ -115,7 +111,7 @@ function requestContextFromValues(values: {/*** Whether to auto-switch the reviewer scope to Entire project on first load. True only for the- * primary section (Needs a PR under the redesign, the Pull requests list with the flag off) when+ * primary section (Needs decision under the redesign, the Pull requests list with the flag off) when* the user is still on the (default) For-you scope, hasn't chosen a scope themselves, has resolved* to a real user, and has zero reports suggested to them — so a user with nothing assigned doesn't* land on an empty inbox. Pure so the branching is unit-testable without mounting the logic.@@ -152,7 +148,6 @@ export interface reportListLogicValues {count: number | nullcountLoading: booleanhasMore: boolean- hiddenReportCount: numberisLoaded: booleanlistApiParams: anyloadedContext: {@@ -160,14 +155,13 @@ export interface reportListLogicValues {scope: InboxScope} | nullloadedQueryKey: string | null+ pageLoadFailed: booleanprimarySectionKey: InboxReportSectionKeyreports: SignalReport[]reportsLoadFailed: booleanreportsResponse: ReportListResponse | nullreportsResponseLoading: booleantotalCount: number | null- visibleCount: number- visibleReports: SignalReport[]}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -290,9 +284,6 @@ export interface reportListLogicActions {restoreReport: (reportId: string) => {reportId: string}- showMore: () => {- value: true- }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -312,8 +303,6 @@ export interface reportListLogicMeta {arg: any) => anyreports: (reportsResponse: ReportListResponse | null) => SignalReport[]- visibleReports: (reports: SignalReport[], visibleCount: number) => SignalReport[]- hiddenReportCount: (totalCount: number | null, count: number | null, visibleReports: SignalReport[]) => numberhasMore: (reportsResponse: ReportListResponse | null) => booleanisLoaded: (reportsResponse: ReportListResponse | null) => booleantotalCount: (reportsResponse: ReportListResponse | null) => number | null@@ -333,14 +322,15 @@ export type reportListLogicType = MakeLogicType<>/**- * Keyed per-section report list. Mounted once per Reports section (Review and merge / Needs a PR /- * Resolved / Not actionable), each with its own fixed `listParams`, so every section is its own- * filtered request with its own accurate `count` and its own pagination. The shared user chrome- * (search, sort, source, priority, reviewer scope) is connected from `inboxFiltersLogic` and applied- * on top, so one filter row drives all four.+ * Keyed per-state report list. Mounted once per report state (Review and merge / Needs decision /+ * Resolved / Dismissed / Not actionable), each with its own fixed `listParams`, so every state is+ * its own filtered request with its own accurate `count` and its own pagination. The shared user+ * chrome (search, sort, source, priority, reviewer scope) is connected from `inboxFiltersLogic` and+ * applied on top, so one filter row drives all of them. The flat Reports list merges the loaded+ * rows of the states the user selected; the legacy tabs render one instance each.*- * `count` loads on mount (cheap `limit=1`) so a section header is correct even while collapsed. The- * rows load lazily (`ensureLoaded`) only once the section is expanded.+ * `count` loads on mount (cheap `limit=1`) so state counts are available before any rows are. The+ * rows load lazily (`ensureLoaded`) only once a surface actually renders the state.*/export const reportListLogic = kea<reportListLogicType>([path((sectionKey) => ['scenes', 'inbox', 'logics', 'reportListLogic', sectionKey]),@@ -390,16 +380,21 @@ export const reportListLogic = kea<reportListLogicType>([restoreReport: (reportId: string) => ({ reportId }),removeReport: (reportId: string) => ({ reportId }),refresh: true,- showMore: true,}),loaders(({ values }) => ({- // Cheap count-only request (limit=1) – populates the section header before its rows load.+ // Cheap count-only request – populates the state's count before its rows load. `count_only`+ // lets the backend answer with one `COUNT(*)`, skipping ordering, row serialization, and+ // the per-row metadata lookups.count: [null as number | null,{loadCount: async () => {- const response = await api.signalReports.list({ ...values.listApiParams, limit: 1 })+ const response = await api.signalReports.list({+ ...values.listApiParams,+ limit: 1,+ count_only: 'true',+ })return response.count},},@@ -450,6 +445,10 @@ export const reportListLogic = kea<reportListLogicType>([},count: {removeReport: (state) => (state != null ? Math.max(0, state - 1) : state),+ // A page response carries the same query's total, so reuse it instead of letting the+ // separately-loaded count disagree with the rows on screen.+ loadReportsSuccess: (_, { reportsResponse }) => reportsResponse.count,+ loadMoreReportsSuccess: (_, { reportsResponse }) => reportsResponse.count,},// The first-page load failed. Kea loaders keep `reportsResponse` null on failure, so// `isLoaded` stays false and the section would otherwise show a skeleton forever. Reset when a@@ -463,19 +462,22 @@ export const reportListLogic = kea<reportListLogicType>([loadReportsFailure: () => true,},],- // How many of the loaded rows this section renders. Reset whenever the list is re-fetched- // from the top (first load, refresh, any filter change), so a new query starts short again.- visibleCount: [- SECTION_PAGE_SIZE,+ // A next-page fetch failed. The loaded rows and `hasMore` are unchanged, and the scroll+ // sentinel may sit inside the viewport without re-firing, so the list must offer an explicit+ // retry. Cleared when a page request starts or lands.+ pageLoadFailed: [+ false,{- showMore: (state) => state + SECTION_PAGE_SIZE,- loadReports: () => SECTION_PAGE_SIZE,+ loadReports: () => false,+ loadMoreReports: () => false,+ loadMoreReportsSuccess: () => false,+ loadMoreReportsFailure: () => true,},],}),selectors({- // The section whose For-you count decides the default scope: Needs a PR under the redesign,+ // The section whose For-you count decides the default scope: Needs decision under the redesign,// the Pull requests list with the flag off (see `shouldDefaultToEntireProject`).primarySectionKey: [(s) => [s.featureFlags],@@ -525,26 +527,6 @@ export const reportListLogic = kea<reportListLogicType>([(s) => [s.reportsResponse],(reportsResponse: ReportListResponse | null): SignalReport[] => reportsResponse?.results ?? [],],- // The rows the section actually renders.- visibleReports: [- (s) => [s.reports, s.visibleCount],- (reports: SignalReport[], visibleCount: number): SignalReport[] => reports.slice(0, visibleCount),- ],- /**- * How many matching reports this section is holding back — what "Show more" promises. Reads- * the loaded response's own total first so it can't disagree with the rows on screen; the- * separately-loaded header count is the fallback while the first page is still in flight.- * Subtract the rows actually on screen (`visibleReports.length`), not the window size- * (`visibleCount`): "Show more" widens the window past the loaded rows before the next page- * lands, so a page still in flight or one that failed to load leaves `visibleCount` ahead of- * `reports.length`. Using the window size there would drive this to 0 and unmount the button,- * stranding the unloaded rows with no way to retry.- */- hiddenReportCount: [- (s) => [s.totalCount, s.count, s.visibleReports],- (totalCount: number | null, count: number | null, visibleReports: SignalReport[]): number =>- Math.max(0, (totalCount ?? count ?? 0) - visibleReports.length),- ],hasMore: [(s) => [s.reportsResponse],(reportsResponse: ReportListResponse | null): boolean =>@@ -607,19 +589,6 @@ export const reportListLogic = kea<reportListLogicType>([actions.loadMoreReports()}},- // The reducer has already widened the window. Only reach for another server page when the- // window now extends past the rows in hand.- showMore: () => {- // The reducer already widened the window, so `hidden_count` is what is still held back.- captureInboxReportAction({- actionType: 'show_more',- surface: 'list_row',- extra: { section: props.sectionKey, hidden_count: values.hiddenReportCount },- })- if (values.visibleCount > values.reports.length) {- actions.loadMore()- }- },refresh: () => {actions.loadCount()if (values.isLoaded) {@@ -692,7 +661,7 @@ export const reportListLogic = kea<reportListLogicType>([lemonToast.success('Report restored to inbox')// Restore maps through restore_target_status server-side, so the report lands back in// whichever section its pre-suppression status names (a report suppressed while ready- // returns to Needs a PR / Review and merge). Broadcast so every mounted section+ // returns to Needs decision / Review and merge). Broadcast so every mounted section// reconciles — this one loses the row, the destination gains it and its count — not// just the section that owns the action.inboxBulkActionsLogic.actions.reportStateChanged()diff --git a/products/signals/frontend/inbox/types.ts b/products/signals/frontend/inbox/types.tsindex 493b4506e9c1..d021f926065a 100644--- a/products/signals/frontend/inbox/types.ts+++ b/products/signals/frontend/inbox/types.ts@@ -236,13 +236,13 @@ export const INBOX_LEGACY_TAB_DESCRIPTION: Record<InboxTabKey, string> = {}/**- * The sections of the Reports list, in render order: work waiting on you first, then work waiting- * on an agent. Each is a collapsible run of report cards with- * its own fixed server filter (see `INBOX_REPORT_SECTION_LIST_PARAMS`), keyed `reportListLogic`- * instance, header count, and pagination — the sections stack in one column rather than switching.- * pinned: these keys are the `tab` property on the inbox analytics events, the `data-attr` on each- * section header, and the keys of the persisted expanded/collapsed state, so they outlive renames of- * the labels above them (`needs-decision` is now "Needs a PR", `monitoring` is "Review and merge").+ * The report states of the Reports list, in filter order: work waiting on you first, then work+ * waiting on an agent, then the closed states. Each has its own fixed server filter (see+ * `INBOX_REPORT_SECTION_LIST_PARAMS`), keyed `reportListLogic` instance, count, and pagination;+ * the flat list merges the rows of the states the state filter selects.+ * pinned: these keys are the `tab` property on the inbox analytics events and the values of the+ * `state` URL filter param, so they outlive renames of the labels above them (`monitoring` is+ * now "Review and merge").*/export const INBOX_REPORT_SECTION_KEYS = ['monitoring',@@ -261,13 +261,13 @@ export const INBOX_PRIMARY_REPORT_SECTION_KEY: InboxReportSectionKey = 'needs-deexport const INBOX_REPORT_SECTION_LABEL: Record<InboxReportSectionKey, string> = {monitoring: 'Review and merge',- 'needs-decision': 'Needs a PR',+ 'needs-decision': 'Needs decision',resolved: 'Resolved',dismissed: 'Dismissed','not-actionable': 'Not actionable',}-/** One line per section, shown as a tooltip when hovering its header. */+/** One line per state, shown as a tooltip on its state-filter option. */export const INBOX_REPORT_SECTION_DESCRIPTION: Record<InboxReportSectionKey, string> = {monitoring: 'Reports with a pull request open, ready for you to review and merge on GitHub.','needs-decision': 'Reports an agent can act on that have no pull request yet.',@@ -279,12 +279,12 @@ export const INBOX_REPORT_SECTION_DESCRIPTION: Record<InboxReportSectionKey, str}/**- * Sections only rendered for staff users (internal). Not actionable is an internal triage surface;- * every other section is public to any team member.+ * States only rendered for staff users (internal). Not actionable is an internal triage surface;+ * every other state is public to any team member.*/export const INBOX_STAFF_ONLY_REPORT_SECTION_KEYS: InboxReportSectionKey[] = ['not-actionable']-/** Small tag rendered next to a section's label in its header. */+/** Small tag rendered next to a state's label in the state filter. */export const INBOX_REPORT_SECTION_TAG: Partial<Record<InboxReportSectionKey, 'Staff'>> = {'not-actionable': 'Staff',}diff --git a/products/signals/frontend/inbox/utils/flatReportList.ts b/products/signals/frontend/inbox/utils/flatReportList.tsnew file mode 100644index 000000000000..f1b44d17e5f1--- /dev/null+++ b/products/signals/frontend/inbox/utils/flatReportList.ts@@ -0,0 +1,60 @@+import type { InboxSortDirection, InboxSortField } from '../logics/inboxFiltersLogic'+import {+ INBOX_REPORT_SECTION_KEYS,+ INBOX_STAFF_ONLY_REPORT_SECTION_KEYS,+ InboxReportSectionKey,+ SignalReport,+} from '../types'+import { compareSignalReports } from './reportOrdering'++/** One row of the flat Reports list: the report and the state whose response contributed it. */+export interface MergedReportRow {+ report: SignalReport+ sectionKey: InboxReportSectionKey+}++/**+ * The states the flat Reports list shows, in canonical order: the state filter's selection when it+ * has one, every state the user can see otherwise. Shared by the list itself and by the analytics+ * rank lookup in `inboxSceneLogic`, so an opened report's rank is computed over the same rows the+ * user saw.+ */+export function selectedFlatListSections(+ visibleStateFilter: InboxReportSectionKey[],+ isStaff: boolean+): InboxReportSectionKey[] {+ const visibleSections = INBOX_REPORT_SECTION_KEYS.filter(+ (key) => isStaff || !INBOX_STAFF_ONLY_REPORT_SECTION_KEYS.includes(key)+ )+ return visibleStateFilter.length > 0+ ? visibleSections.filter((key) => visibleStateFilter.includes(key))+ : visibleSections+}++/**+ * The flat list's rows: the loaded rows of every selected state, deduplicated (a report can match+ * two states' filters, e.g. a PR'd report judged not actionable is in both Review and merge and the+ * staff Not actionable state; the first state in canonical order claims it), then ordered with the+ * same keys the server sorted each response by. Rows past a state's loaded page can sort below+ * later-keyed rows from a shorter state until the next page lands; the scroll sentinel keeps every+ * selected state paging together.+ */+export function mergeReportRows(+ reportsBySection: Record<InboxReportSectionKey, SignalReport[]>,+ selectedSections: InboxReportSectionKey[],+ sortField: InboxSortField,+ sortDirection: InboxSortDirection+): MergedReportRow[] {+ const seen = new Set<string>()+ const rows: MergedReportRow[] = []+ for (const sectionKey of selectedSections) {+ for (const report of reportsBySection[sectionKey]) {+ if (!seen.has(report.id)) {+ seen.add(report.id)+ rows.push({ report, sectionKey })+ }+ }+ }+ const compare = compareSignalReports(sortField, sortDirection)+ return rows.sort((a, b) => compare(a.report, b.report))+}diff --git a/products/signals/frontend/inbox/utils/reportOrdering.test.ts b/products/signals/frontend/inbox/utils/reportOrdering.test.tsnew file mode 100644index 000000000000..259fe28da5da--- /dev/null+++ b/products/signals/frontend/inbox/utils/reportOrdering.test.ts@@ -0,0 +1,70 @@+import { SignalReport, SignalReportStatus } from '../types'+import { compareSignalReports } from './reportOrdering'++function report(id: string, overrides: Partial<SignalReport>): SignalReport {+ return {+ id,+ title: id,+ summary: null,+ status: SignalReportStatus.READY,+ total_weight: 0,+ signal_count: 1,+ relevant_user_count: null,+ artefact_count: 0,+ is_suggested_reviewer: false,+ priority: 'P2',+ created_at: '2026-06-01T10:00:00Z',+ updated_at: '2026-06-01T10:00:00Z',+ ...overrides,+ }+}++describe('compareSignalReports', () => {+ // The merged list must order rows from different per-state responses the way the server ordered+ // each response, or reports jump around relative to the sectioned queries they came from.+ it('sorts by priority, then status rank, then recency', () => {+ const rows = [+ report('resolved-p0', { priority: 'P0', status: SignalReportStatus.RESOLVED }),+ report('ready-p2-old', { priority: 'P2', updated_at: '2026-06-01T10:00:00Z' }),+ report('ready-p2-new', { priority: 'P2', updated_at: '2026-06-02T10:00:00Z' }),+ report('unprioritized', { priority: null }),+ report('ready-p0', { priority: 'P0' }),+ report('not-actionable-p0', { priority: 'P0', actionability: 'not_actionable' }),+ ]+ rows.sort(compareSignalReports('priority', 'asc'))+ expect(rows.map((r) => r.id)).toEqual([+ // Within P0: ready (rank 0) before ready-not-actionable (1) before resolved (7).+ 'ready-p0',+ 'not-actionable-p0',+ 'resolved-p0',+ // Within P2: newer updated_at first.+ 'ready-p2-new',+ 'ready-p2-old',+ // Missing priority coalesces after P4, like the server's "~".+ 'unprioritized',+ ])+ })++ it('flips only the selected field for desc, keeping the status and recency tiebreaks', () => {+ const rows = [+ report('old-resolved', { created_at: '2026-06-01T00:00:00Z', status: SignalReportStatus.RESOLVED }),+ report('new-ready', { created_at: '2026-06-03T00:00:00Z' }),+ report('new-resolved', { created_at: '2026-06-03T00:00:00Z', status: SignalReportStatus.RESOLVED }),+ ]+ rows.sort(compareSignalReports('created_at', 'desc'))+ expect(rows.map((r) => r.id)).toEqual(['new-ready', 'new-resolved', 'old-resolved'])+ })++ // DRF omits the fractional seconds when the microseconds are zero, and plain string order then+ // puts the zero-microsecond row after every fractional one in the same second.+ it('orders zero-microsecond timestamps against fractional ones like the database', () => {+ const rows = [+ report('fractional', { created_at: '2026-06-01T00:00:00.100000Z' }),+ report('whole-second', { created_at: '2026-06-01T00:00:00Z' }),+ ]+ rows.sort(compareSignalReports('created_at', 'asc'))+ expect(rows.map((r) => r.id)).toEqual(['whole-second', 'fractional'])+ rows.sort(compareSignalReports('created_at', 'desc'))+ expect(rows.map((r) => r.id)).toEqual(['fractional', 'whole-second'])+ })+})diff --git a/products/signals/frontend/inbox/utils/reportOrdering.ts b/products/signals/frontend/inbox/utils/reportOrdering.tsnew file mode 100644index 000000000000..365ef764c56f--- /dev/null+++ b/products/signals/frontend/inbox/utils/reportOrdering.ts@@ -0,0 +1,70 @@+import type { InboxSortDirection, InboxSortField } from '../logics/inboxFiltersLogic'+import { SignalReport, SignalReportStatus } from '../types'++/**+ * Client-side mirror of the server list ordering (`buildSignalReportListOrdering`): the selected+ * field leads, then the pipeline status rank, then recency. The flat Reports list merges several+ * per-state responses, so rows from different requests must be comparable with the same keys the+ * server sorted each response by.+ */++// Mirrors `_annotate_signal_report_status_rank` in products/signals/backend/views.py. `ready`+// splits into two virtual stages there: 0 for actionable (or unjudged), 1 for not actionable.+const STATUS_RANK: Record<SignalReportStatus, number> = {+ [SignalReportStatus.READY]: 0,+ [SignalReportStatus.PENDING_INPUT]: 2,+ [SignalReportStatus.IN_PROGRESS]: 3,+ [SignalReportStatus.CANDIDATE]: 4,+ [SignalReportStatus.POTENTIAL]: 5,+ [SignalReportStatus.FAILED]: 6,+ [SignalReportStatus.RESOLVED]: 7,+ [SignalReportStatus.SUPPRESSED]: 8,+ [SignalReportStatus.DELETED]: 9,+}++function statusRank(report: SignalReport): number {+ if (report.status === SignalReportStatus.READY && report.actionability === 'not_actionable') {+ return 1+ }+ return STATUS_RANK[report.status] ?? 50+}++// The server coalesces a missing priority to "~", which sorts after "P4" in ASCII.+function priorityKey(report: SignalReport): string {+ return report.priority ?? '~'+}++// Plain code-point comparison, matching how Postgres sorts the ISO timestamps and P0–P4 strings.+function compareStrings(a: string, b: string): number {+ return a < b ? -1 : a > b ? 1 : 0+}++// DRF omits the fractional part when the microseconds are zero, and a plain string comparison then+// puts "...:00Z" after "...:00.100000Z". Pad the missing fraction so the comparison matches the+// database order.+function timestampKey(value: string): string {+ return value.includes('.') ? value : value.replace(/(Z|[+-]\d\d:?\d\d)$/, '.000000$1')+}++/** Comparator over reports for the given sort selection. Stable input order breaks remaining ties. */+export function compareSignalReports(+ field: InboxSortField,+ direction: InboxSortDirection+): (a: SignalReport, b: SignalReport) => number {+ const dir = direction === 'desc' ? -1 : 1+ return (a, b) => {+ 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) {+ return rank+ }+ // Recency tiebreak, skipped when the selected field already is updated_at.+ return field === 'updated_at' ? 0 : compareStrings(timestampKey(b.updated_at), timestampKey(a.updated_at))+ }+}