: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
fix(desktop): count the inbox Reports badge instead of deriving it (#78963)
Andrew Maguire49e86b528379
diff --git a/products/desktop/packages/core/src/inbox/reportFiltering.ts b/products/desktop/packages/core/src/inbox/reportFiltering.tsindex 2a8271b2cbbf..a3edb87b5c7f 100644--- a/products/desktop/packages/core/src/inbox/reportFiltering.ts+++ b/products/desktop/packages/core/src/inbox/reportFiltering.ts@@ -40,6 +40,16 @@ export const INBOX_DISMISSED_STATUS_FILTER = "suppressed,resolved";*/export const INBOX_PULL_REQUEST_STATUS_FILTER = "ready";+/**+ * Status filter for the Reports tab's count. `isReportTabReport` keeps a report+ * only when it is `ready` and carries no PR, because every other pipeline status+ * is either a queued/live run that belongs to the Runs tab or a `failed` run+ * that is filtered out. Pairing this with `has_implementation_pr: false`+ * reproduces that predicate server-side, so the badge can be counted rather than+ * derived from the loaded pages.+ */+export const INBOX_REPORTS_TAB_STATUS_FILTER = "ready";+/** Polling interval for inbox queries while the Electron window is focused. */export const INBOX_REFETCH_INTERVAL_MS = 3000;diff --git a/products/desktop/packages/ui/src/features/inbox/components/InboxView.tsx b/products/desktop/packages/ui/src/features/inbox/components/InboxView.tsxindex 957f0dcf92cf..a6e174050314 100644--- a/products/desktop/packages/ui/src/features/inbox/components/InboxView.tsx+++ b/products/desktop/packages/ui/src/features/inbox/components/InboxView.tsx@@ -40,7 +40,7 @@ export function InboxView() {useTrackInboxViewed();- const { counts } = useInboxAllReports();+ const { counts } = useInboxAllReports({ withReportsCount: true });const pathname = useRouterState({ select: (s) => s.location.pathname });const isDetailView = isInboxDetailPath(pathname);diff --git a/products/desktop/packages/ui/src/features/inbox/hooks/useInboxAllReports.test.tsx b/products/desktop/packages/ui/src/features/inbox/hooks/useInboxAllReports.test.tsxnew file mode 100644index 000000000000..680161511867--- /dev/null+++ b/products/desktop/packages/ui/src/features/inbox/hooks/useInboxAllReports.test.tsx@@ -0,0 +1,132 @@+import { INBOX_SCOPE_ENTIRE_PROJECT } from "@posthog/core/inbox/reportMembership";+import type {+ SignalReport,+ SignalReportsQueryParams,+ SignalReportsResponse,+} from "@posthog/shared/domain-types";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { renderHook, waitFor } from "@testing-library/react";+import type { ReactNode } from "react";+import { beforeEach, describe, expect, it, vi } from "vitest";++const PIPELINE_TOTAL = 240;+const PULL_REQUEST_TOTAL = 40;+const REPORT_TAB_TOTAL = 75;++const mockGetSignalReports = vi.hoisted(() => vi.fn());+const mockClient = vi.hoisted(() => ({+ getSignalReports: mockGetSignalReports,+}));++vi.mock("@posthog/ui/features/auth/authClient", () => ({+ useOptionalAuthenticatedClient: () => mockClient,+}));++vi.mock("@posthog/ui/features/auth/useCurrentUser", () => ({+ AUTH_SCOPED_QUERY_META: {},+ useCurrentUser: () => ({ data: { uuid: "user-1" } }),+}));++vi.mock("@posthog/ui/features/inbox/stores/inboxReviewerScopeStore", () => ({+ useInboxReviewerScopeStore: (+ selector: (state: { scope: string }) => unknown,+ ) => selector({ scope: INBOX_SCOPE_ENTIRE_PROJECT }),+}));++vi.mock("@posthog/ui/features/inbox/stores/inboxSignalsFilterStore", () => ({+ useInboxSignalsFilterStore: (selector: (state: unknown) => unknown) =>+ selector({+ searchQuery: "",+ sortField: "priority",+ sortDirection: "desc",+ sourceProductFilter: [],+ priorityFilter: [],+ }),+}));++import { useInboxAllReports } from "./useInboxAllReports";++function readyReport(index: number): SignalReport {+ return {+ id: `report-${index}`,+ title: `Report ${index}`,+ summary: null,+ status: "ready",+ total_weight: 1,+ signal_count: 1,+ created_at: "2024-01-01T00:00:00Z",+ updated_at: "2024-01-01T00:00:00Z",+ artefact_count: 0,+ implementation_pr_url: null,+ };+}++/**+ * Answers the three distinct queries the hook fires. The pipeline page is all+ * `ready` reports with no PR, which is what the server's status-ranked ordering+ * actually returns first, and is the condition under which deriving the Reports+ * badge by subtraction silently overcounts.+ */+function fakeServer(params?: SignalReportsQueryParams): SignalReportsResponse {+ if (params?.has_implementation_pr === true) {+ return { count: PULL_REQUEST_TOTAL, results: [] };+ }+ if (params?.has_implementation_pr === false) {+ return { count: REPORT_TAB_TOTAL, results: [] };+ }+ return {+ count: PIPELINE_TOTAL,+ results: Array.from({ length: 100 }, (_, i) => readyReport(i)),+ };+}++/** Params of the Reports-count request, or undefined if it was never fired. */+function reportsCountParams(): SignalReportsQueryParams | undefined {+ for (const [params] of mockGetSignalReports.mock.calls) {+ if (params?.has_implementation_pr === false) return params;+ }+ return undefined;+}++function renderCounts(options?: { withReportsCount?: boolean }) {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ const wrapper = ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ );+ return renderHook(() => useInboxAllReports(options), { wrapper });+}++describe("useInboxAllReports", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockGetSignalReports.mockImplementation(async (params) =>+ fakeServer(params),+ );+ });++ it("counts Reports from the server, not by subtracting from the pipeline total", async () => {+ const { result } = renderCounts({ withReportsCount: true });++ await waitFor(() => {+ expect(result.current.counts.reports).toBe(REPORT_TAB_TOTAL);+ });+ expect(result.current.counts.pulls).toBe(PULL_REQUEST_TOTAL);++ // Anything wider than `ready` pulls in the queued, live and failed runs that+ // the Reports tab routes elsewhere, which is what made the badge disagree+ // with the list it labels.+ expect(reportsCountParams()?.status).toBe("ready");+ });++ it("skips the Reports count query for consumers that only read the pulls badge", async () => {+ const { result } = renderCounts();++ await waitFor(() => {+ expect(result.current.counts.pulls).toBe(PULL_REQUEST_TOTAL);+ });+ expect(result.current.counts.reports).toBe(0);+ expect(reportsCountParams()).toBeUndefined();+ });+});diff --git a/products/desktop/packages/ui/src/features/inbox/hooks/useInboxAllReports.ts b/products/desktop/packages/ui/src/features/inbox/hooks/useInboxAllReports.tsindex 99f19b7a33d7..0f55ab8f4b7f 100644--- a/products/desktop/packages/ui/src/features/inbox/hooks/useInboxAllReports.ts+++ b/products/desktop/packages/ui/src/features/inbox/hooks/useInboxAllReports.ts@@ -6,12 +6,10 @@ import {INBOX_PIPELINE_STATUS_FILTER,INBOX_PULL_REQUEST_STATUS_FILTER,INBOX_REFETCH_INTERVAL_MS,+ INBOX_REPORTS_TAB_STATUS_FILTER,} from "@posthog/core/inbox/reportFiltering";import {INBOX_SCOPE_FOR_YOU,- isExcludedFromInbox,- isPullRequestReport,- isReportTabReport,parseTeammateInboxScope,} from "@posthog/core/inbox/reportMembership";import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";@@ -37,11 +35,18 @@ const EMPTY_FILTER_ARRAY: never[] = [];** When `ignoreFilters` is set, the filter-store selectors return constant* values so unrelated filter changes don't re-render the consumer.+ *+ * `withReportsCount` opts into the extra count query behind `counts.reports`;+ * without it that count stays 0. Only the inbox tab bar renders it, and the+ * sidebar and channel nav mount this hook on every route to read `counts.pulls`+ * alone, so making it opt-in keeps them from polling a second endpoint for a+ * number they never show.*/export function useInboxAllReports(options?: {ignoreScope?: boolean;ignoreFilters?: boolean;pullRequestsOnly?: boolean;+ withReportsCount?: boolean;refetchIntervalMs?: number;}) {const ignoreScope = options?.ignoreScope ?? false;@@ -53,6 +58,7 @@ export function useInboxAllReports(options?: {// sitting past the broad list's first page no longer renders an empty tab// under a positive badge.const pullRequestsOnly = options?.pullRequestsOnly ?? false;+ const withReportsCount = options?.withReportsCount ?? false;const scope = useInboxReviewerScopeStore((s) => s.scope);const searchQuery = useInboxSignalsFilterStore((s) =>ignoreFilters ? "" : s.searchQuery,@@ -139,6 +145,33 @@ export function useInboxAllReports(options?: {);const pullRequestTotal = pullRequestCountQuery.data?.count ?? 0;+ // True count of Reports-tab reports for the active scope, on the same+ // `limit: 1` pattern as the pull-request count above. Deriving it instead by+ // subtracting from the pipeline total only works if every non-report item is+ // visible in the loaded pages, and the list is ordered `ready` first, so the+ // queued, live and failed runs sit past page 1 and never get subtracted.+ const reportsCountQuery = useInboxReports(+ {+ status: INBOX_REPORTS_TAB_STATUS_FILTER,+ has_implementation_pr: false,+ source_product:+ sourceProductFilter.length > 0+ ? sourceProductFilter.join(",")+ : undefined,+ priority: buildPriorityFilterParam(priorityFilter),+ suggested_reviewers: reviewerUuid+ ? buildSuggestedReviewerFilterParam([reviewerUuid])+ : undefined,+ limit: 1,+ },+ {+ enabled: withReportsCount && (!isForYou || reviewerUuid != null),+ refetchInterval: refetchIntervalMs,+ refetchIntervalInBackground: false,+ },+ );+ const reportsTotal = reportsCountQuery.data?.count ?? 0;+const scopedReports = useMemo(() => {// Reviewer scope is already applied server-side via `suggested_reviewers`.// Don't re-filter on the `is_suggested_reviewer` boolean — it can disagree@@ -148,30 +181,26 @@ export function useInboxAllReports(options?: {: query.allReports;}, [query.allReports, searchQuery]);- const counts = useMemo(() => {- // Derive Reports from the backend total (the loaded list caps at the page- // size), subtracting PRs and the other non-report items the total includes.- // Scope is server-side, so no client reviewer recheck here either.- const loadedOtherNonReport = query.allReports.filter(- (r) =>- !isExcludedFromInbox(r) &&- !isReportTabReport(r) &&- !isPullRequestReport(r),- ).length;- return {- // True backend counts, unaffected by the list's page-size cap.- pulls: pullRequestTotal,- reports: Math.max(- 0,- query.totalCount - pullRequestTotal - loadedOtherNonReport,- ),- };- }, [query.allReports, query.totalCount, pullRequestTotal]);+ // Both are backend counts under the same server-side scope and filters as the+ // list, so they are unaffected by its page-size cap and need no client-side+ // reviewer recheck.+ const counts = useMemo(+ () => ({ pulls: pullRequestTotal, reports: reportsTotal }),+ [pullRequestTotal, reportsTotal],+ );++ // Each count is its own request, so the list can succeed while they are still+ // in flight and `counts` still reads 0. Anything that records the counts once+ // and never revises them has to wait for this rather than for the list.+ const countsReady =+ pullRequestCountQuery.isSuccess &&+ (!withReportsCount || reportsCountQuery.isSuccess);return {...query,scopedReports,counts,+ countsReady,scope,// The effective filter values used for this query. Surfaced so consumers// (e.g. analytics) can read them without subscribing to the filter store adiff --git a/products/desktop/packages/ui/src/features/inbox/hooks/useTrackInboxViewed.test.tsx b/products/desktop/packages/ui/src/features/inbox/hooks/useTrackInboxViewed.test.tsxnew file mode 100644index 000000000000..216aa3d7f502--- /dev/null+++ b/products/desktop/packages/ui/src/features/inbox/hooks/useTrackInboxViewed.test.tsx@@ -0,0 +1,151 @@+import { INBOX_SCOPE_ENTIRE_PROJECT } from "@posthog/core/inbox/reportMembership";+import type {+ SignalReport,+ SignalReportsQueryParams,+ SignalReportsResponse,+} from "@posthog/shared/domain-types";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { renderHook, waitFor } from "@testing-library/react";+import type { ReactNode } from "react";+import { beforeEach, describe, expect, it, vi } from "vitest";++const PIPELINE_TOTAL = 240;+const PULL_REQUEST_TOTAL = 40;+const REPORT_TAB_TOTAL = 75;++const mockGetSignalReports = vi.hoisted(() => vi.fn());+const mockTrack = vi.hoisted(() => vi.fn());++vi.mock("@posthog/ui/features/auth/authClient", () => ({+ useOptionalAuthenticatedClient: () => ({+ getSignalReports: mockGetSignalReports,+ }),+}));++vi.mock("@posthog/ui/features/auth/useCurrentUser", () => ({+ AUTH_SCOPED_QUERY_META: {},+ useCurrentUser: () => ({ data: { uuid: "user-1" } }),+}));++vi.mock("@posthog/ui/shell/analytics", () => ({ track: mockTrack }));++vi.mock("@posthog/ui/features/inbox/stores/inboxReviewerScopeStore", () => ({+ useInboxReviewerScopeStore: (+ selector: (state: { scope: string }) => unknown,+ ) => selector({ scope: INBOX_SCOPE_ENTIRE_PROJECT }),+}));++vi.mock("@posthog/ui/features/inbox/stores/inboxSignalsFilterStore", () => ({+ useInboxSignalsFilterStore: (selector: (state: unknown) => unknown) =>+ selector({+ searchQuery: "",+ sortField: "priority",+ sortDirection: "desc",+ sourceProductFilter: [],+ priorityFilter: [],+ }),+}));++import { useInboxAllReports } from "./useInboxAllReports";+import { useTrackInboxViewed } from "./useTrackInboxViewed";++function readyReport(index: number): SignalReport {+ return {+ id: `report-${index}`,+ title: `Report ${index}`,+ summary: null,+ status: "ready",+ total_weight: 1,+ signal_count: 1,+ created_at: "2024-01-01T00:00:00Z",+ updated_at: "2024-01-01T00:00:00Z",+ artefact_count: 0,+ implementation_pr_url: null,+ };+}++function fakeServer(params?: SignalReportsQueryParams): SignalReportsResponse {+ if (params?.has_implementation_pr === true) {+ return { count: PULL_REQUEST_TOTAL, results: [] };+ }+ if (params?.has_implementation_pr === false) {+ return { count: REPORT_TAB_TOTAL, results: [] };+ }+ return {+ count: PIPELINE_TOTAL,+ results: Array.from({ length: 100 }, (_, i) => readyReport(i)),+ };+}++/**+ * Renders the tracker with a probe alongside it, so tests can await the list's+ * load state. The probe deliberately omits `withReportsCount`: opting in here+ * would enable the count query itself, and the tracker would then read it from+ * the cache even when the tracker never asked for it.+ */+function renderTracker() {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ const wrapper = ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ );+ return renderHook(+ () => {+ useTrackInboxViewed();+ return useInboxAllReports();+ },+ { wrapper },+ );+}++function trackedProperties(): Record<string, unknown> {+ return mockTrack.mock.calls[0][1] as Record<string, unknown>;+}++describe("useTrackInboxViewed", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockGetSignalReports.mockImplementation(async (params) =>+ fakeServer(params),+ );+ });++ it("records the tab counts the badges show", async () => {+ renderTracker();++ await waitFor(() => expect(mockTrack).toHaveBeenCalledTimes(1));+ expect(trackedProperties()).toMatchObject({+ pulls_tab_count: PULL_REQUEST_TOTAL,+ reports_tab_count: REPORT_TAB_TOTAL,+ });+ });++ it("holds the one-shot event until the count requests land", async () => {+ let releaseReportsCount: (response: SignalReportsResponse) => void =+ () => {};+ const pendingReportsCount = new Promise<SignalReportsResponse>(+ (resolve) => {+ releaseReportsCount = resolve;+ },+ );+ mockGetSignalReports.mockImplementation((params) =>+ params?.has_implementation_pr === false+ ? pendingReportsCount+ : Promise.resolve(fakeServer(params)),+ );++ const { result } = renderTracker();++ // The list resolving first is the whole point: the event must not fire on it.+ await waitFor(() => expect(result.current.isSuccess).toBe(true));+ expect(mockTrack).not.toHaveBeenCalled();++ releaseReportsCount({ count: REPORT_TAB_TOTAL, results: [] });++ await waitFor(() => expect(mockTrack).toHaveBeenCalledTimes(1));+ expect(trackedProperties()).toMatchObject({+ reports_tab_count: REPORT_TAB_TOTAL,+ });+ });+});diff --git a/products/desktop/packages/ui/src/features/inbox/hooks/useTrackInboxViewed.ts b/products/desktop/packages/ui/src/features/inbox/hooks/useTrackInboxViewed.tsindex f586f5fcbfcd..2121a73aea1a 100644--- a/products/desktop/packages/ui/src/features/inbox/hooks/useTrackInboxViewed.ts+++ b/products/desktop/packages/ui/src/features/inbox/hooks/useTrackInboxViewed.ts@@ -21,10 +21,13 @@ export function useTrackInboxViewed(): void {counts,scope,isSuccess,+ countsReady,sourceProductFilter,priorityFilter,searchQuery,- } = useInboxAllReports();+ // The badge counts come from their own requests, so opt in here too or the+ // event records a zero the user never saw.+ } = useInboxAllReports({ withReportsCount: true });const firedRef = useRef(false);useEffect(() => {@@ -33,6 +36,9 @@ export function useTrackInboxViewed(): void {// request also leaves `isLoading` false with an empty list, and `firedRef`// would then lock in a bogus empty-inbox view that a later refetch can't fix.if (!isSuccess) return;+ // The event carries the tab badges and fires once, so a list that settles+ // ahead of the count requests would lock in counts of zero.+ if (!countsReady) return;firedRef.current = true;track(ANALYTICS_EVENTS.INBOX_VIEWED,@@ -51,6 +57,7 @@ export function useTrackInboxViewed(): void {);}, [isSuccess,+ countsReady,scopedReports,totalCount,counts,