: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(desktop): global reports inbox — one triage surface with server-side counts (#87321)
Dylan Martin6e4f23685150
diff --git a/products/desktop/packages/core/src/inbox/reportActions.test.ts b/products/desktop/packages/core/src/inbox/reportActions.test.tsindex 9e81295a3ac9..47f825f39080 100644--- a/products/desktop/packages/core/src/inbox/reportActions.test.ts+++ b/products/desktop/packages/core/src/inbox/reportActions.test.ts@@ -1,7 +1,9 @@+import type { SignalReport } from "@posthog/shared/types";import { describe, expect, it } from "vitest";import {buildCreatePrReportPrompt,buildDiscussReportPrompt,+ canCreateImplementationPr,} from "./reportActions";describe("buildCreatePrReportPrompt", () => {@@ -184,3 +186,18 @@ describe("buildDiscussReportPrompt", () => {expect(withoutQuestion).toMatch(/can't fetch the report/i);});});++describe("canCreateImplementationPr", () => {+ it("a merged PR no longer blocks a fresh attempt, but an open one does", () => {+ const base = {+ id: "r",+ status: "ready",+ actionability: "immediately_actionable",+ implementation_pr_url: "https://gh/pr/1",+ } as Partial<SignalReport> as SignalReport;+ expect(canCreateImplementationPr(base)).toBe(false);+ expect(+ canCreateImplementationPr({ ...base, implementation_pr_merged: true }),+ ).toBe(true);+ });+});diff --git a/products/desktop/packages/core/src/inbox/reportActions.ts b/products/desktop/packages/core/src/inbox/reportActions.tsindex 02af51ff092a..754f113327bd 100644--- a/products/desktop/packages/core/src/inbox/reportActions.ts+++ b/products/desktop/packages/core/src/inbox/reportActions.ts@@ -10,7 +10,11 @@ import type { SignalReport } from "@posthog/shared/types";* Hidden once an implementation PR exists or the issue is already fixed.*/export function canCreateImplementationPr(report: SignalReport): boolean {- if (report.implementation_pr_url) return false;+ // A merged PR doesn't block: a report that outlived its fix (evidence kept+ // arriving) legitimately gets another attempt.+ if (report.implementation_pr_url && !report.implementation_pr_merged) {+ return false;+ }if (report.already_addressed === true) return false;if (report.status === "pending_input") return true;if (report.status === "ready") {diff --git a/products/desktop/packages/core/src/inbox/reportFiltering.ts b/products/desktop/packages/core/src/inbox/reportFiltering.tsindex a3edb87b5c7f..69497d5e7cdf 100644--- a/products/desktop/packages/core/src/inbox/reportFiltering.ts+++ b/products/desktop/packages/core/src/inbox/reportFiltering.ts@@ -40,6 +40,17 @@ export const INBOX_DISMISSED_STATUS_FILTER = "suppressed,resolved";*/export const INBOX_PULL_REQUEST_STATUS_FILTER = "ready";+/**+ * Status filter for the reports inbox page (and its badges). Excludes+ * `potential`: embryonic reports the pipeline hasn't promoted yet, which no+ * surface has ever displayed — fetching them bloats Monitoring with rows+ * nobody can act on and spends the page's row budget on noise. The legacy+ * inbox keeps the broader filter for its Runs accounting.+ */+export const REPORTS_INBOX_STATUS_FILTER = INBOX_PIPELINE_STATUSES.filter(+ (status) => status !== "potential",+).join(",");+/*** 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 statusdiff --git a/products/desktop/packages/core/src/inbox/reportInboxSections.test.ts b/products/desktop/packages/core/src/inbox/reportInboxSections.test.tsnew file mode 100644index 000000000000..d6af28cf1e59--- /dev/null+++ b/products/desktop/packages/core/src/inbox/reportInboxSections.test.ts@@ -0,0 +1,63 @@+import type { SignalReport } from "@posthog/shared/types";+import { describe, expect, it } from "vitest";++import { partitionInboxReports } from "./reportInboxSections";++function report(overrides: Partial<SignalReport>): SignalReport {+ return {+ id: overrides.id ?? "r",+ title: "A report",+ summary: null,+ status: "ready",+ total_weight: 1,+ signal_count: 1,+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-01T00:00:00Z",+ artefact_count: 0,+ ...overrides,+ } as SignalReport;+}++describe("reportInboxSections", () => {+ it.each([+ // The boundary is status alone — the one dimension server counts can+ // reproduce. Ready is a decision whatever else the report carries...+ [{ status: "ready" }, "decision"],+ [{ status: "ready", actionability: "not_actionable" }, "decision"],+ [{ status: "ready", already_addressed: true }, "decision"],+ [+ {+ status: "ready",+ implementation_pr_url: "https://gh/pr/9",+ implementation_pr_merged: true,+ },+ "decision",+ ],+ // ...and anything not ready is monitoring, even mid-run with an open PR.+ [{ status: "pending_input" }, "monitoring"],+ [{ status: "failed" }, "monitoring"],+ [{ status: "in_progress" }, "monitoring"],+ [+ { status: "in_progress", implementation_pr_url: "https://gh/pr/1" },+ "monitoring",+ ],+ [{ status: "candidate" }, "monitoring"],+ ] as const)("%j lands in %s", (overrides, section) => {+ const sections = partitionInboxReports([+ report(overrides as Partial<SignalReport>),+ ]);+ expect(sections.decision.length).toBe(section === "decision" ? 1 : 0);+ expect(sections.monitoring.length).toBe(section === "monitoring" ? 1 : 0);+ });++ it("partition preserves the list's own order within each section", () => {+ const sections = partitionInboxReports([+ report({ id: "d1" }),+ report({ id: "m1", status: "in_progress" }),+ report({ id: "d2" }),+ report({ id: "m2", status: "candidate" }),+ ]);+ expect(sections.decision.map((r) => r.id)).toEqual(["d1", "d2"]);+ expect(sections.monitoring.map((r) => r.id)).toEqual(["m1", "m2"]);+ });+});diff --git a/products/desktop/packages/core/src/inbox/reportInboxSections.ts b/products/desktop/packages/core/src/inbox/reportInboxSections.tsnew file mode 100644index 000000000000..147c0a98e1f4--- /dev/null+++ b/products/desktop/packages/core/src/inbox/reportInboxSections.ts@@ -0,0 +1,42 @@+import type { SignalReport } from "@posthog/shared/types";++/**+ * The global reports inbox shows every live report in two sections. The+ * boundary is deliberately a server-countable dimension — report status —+ * because the section headers and nav badges are server-side count queries,+ * and a boundary the API can't filter on (actionability, PR-merged state)+ * produces headline numbers no query can verify.+ */+export interface InboxReportSections {+ /** Ready: research done, a person decides — act, review the PR, or archive. */+ decision: SignalReport[];+ /** Still moving or stuck: running, queued, waiting on input, failed. */+ monitoring: SignalReport[];+}++/**+ * Whether a report is in the "Needs a decision" section: exactly the `ready`+ * status. Archiving an FYI is a decision too, so ready-but-not-actionable+ * reports stay here (a row-level hint conveys that) rather than defining a+ * section boundary counts can't reproduce.+ */+export function reportNeedsDecision(report: SignalReport): boolean {+ return report.status === "ready";+}++/**+ * Partition the loaded list into the two sections, preserving its order. The+ * list arrives sorted by the user's own sort (applied server-side by the+ * filter bar); section totals come from server count queries, not from this+ * partition — these arrays only feed the rendered rows.+ */+export function partitionInboxReports(+ reports: SignalReport[],+): InboxReportSections {+ const decision: SignalReport[] = [];+ const monitoring: SignalReport[] = [];+ for (const report of reports) {+ (reportNeedsDecision(report) ? decision : monitoring).push(report);+ }+ return { decision, monitoring };+}diff --git a/products/desktop/packages/core/src/inbox/reportPresentation.test.ts b/products/desktop/packages/core/src/inbox/reportPresentation.test.tsindex ffec4e173d87..e9ef0f5127f2 100644--- a/products/desktop/packages/core/src/inbox/reportPresentation.test.ts+++ b/products/desktop/packages/core/src/inbox/reportPresentation.test.ts@@ -10,6 +10,7 @@ import {humanizeReportTitle,isStatusRedundantWithActionability,parseConventionalCommitTitle,+ splitReportSummary,} from "./reportPresentation";describe("isStatusRedundantWithActionability", () => {@@ -232,3 +233,35 @@ describe("humanizeReportTitle", () => {expect(humanizeReportTitle(title, "Untitled")).toBe(expected);});});++describe("splitReportSummary", () => {+ it("splits the lede and each ## section in order, keeping every word", () => {+ const split = splitReportSummary(+ "Users hit a dead end.\n\n## Problem\n\nThe cache never expires.\nStill broken.\n\n## Impact\n\n40 users a day.\n\n## Solution\n\nBound the freshness.",+ );+ expect(split.lede).toBe("Users hit a dead end.");+ expect(split.sections.map((s) => s.title)).toEqual([+ "Problem",+ "Impact",+ "Solution",+ ]);+ expect(split.sections[0].body).toBe(+ "The cache never expires.\nStill broken.",+ );+ expect(split.sections[1].body).toBe("40 users a day.");+ });++ it("returns no sections for heading-less summaries so callers render them whole", () => {+ const split = splitReportSummary(+ "**What's happening:** one paragraph, bold labels, no headings.",+ );+ expect(split.sections).toEqual([]);+ expect(split.lede).toContain("no headings");+ });++ it("handles a summary that opens directly with a heading", () => {+ const split = splitReportSummary("## Problem\n\nIt broke.");+ expect(split.lede).toBe("");+ expect(split.sections).toEqual([{ title: "Problem", body: "It broke." }]);+ });+});diff --git a/products/desktop/packages/core/src/inbox/reportPresentation.ts b/products/desktop/packages/core/src/inbox/reportPresentation.tsindex bc1531cfacbd..581204fd835b 100644--- a/products/desktop/packages/core/src/inbox/reportPresentation.ts+++ b/products/desktop/packages/core/src/inbox/reportPresentation.ts@@ -234,3 +234,52 @@ export function parsePrUrl(prUrl: string): ParsedPrUrl | null {return null;}}++export interface ReportSummarySplit {+ /** Prose before the first `##` heading — the summary's own tl;dr. */+ lede: string;+ /** The `##` sections, in document order, bodies untrimmed of markdown. */+ sections: { title: string; body: string }[];+}++/**+ * Split a report summary into its labeled slots: the tl;dr lede and each+ * `##` section (Problem, Impact, Solution, ...). The reader jumps to the slot+ * they need instead of reconstructing the structure by reading linearly —+ * nothing is cut, it's sorted. Summaries without `##` headings return an+ * empty section list, and callers render them whole.+ */+export function splitReportSummary(+ summary: string | null | undefined,+): ReportSummarySplit {+ if (typeof summary !== "string" || !summary.trim()) {+ return { lede: "", sections: [] };+ }+ const lines = summary.split(/\r?\n/);+ const sections: { title: string; body: string }[] = [];+ const lede: string[] = [];+ let current: { title: string; body: string[] } | null = null;+ for (const line of lines) {+ const heading = /^##\s+(.+?)\s*$/.exec(line);+ if (heading) {+ if (current) {+ sections.push({+ title: current.title,+ body: current.body.join("\n").trim(),+ });+ }+ current = { title: heading[1], body: [] };+ } else if (current) {+ current.body.push(line);+ } else {+ lede.push(line);+ }+ }+ if (current) {+ sections.push({+ title: current.title,+ body: current.body.join("\n").trim(),+ });+ }+ return { lede: lede.join("\n").trim(), sections };+}diff --git a/products/desktop/packages/core/src/inbox/reportVerdict.ts b/products/desktop/packages/core/src/inbox/reportVerdict.tsindex 24cb0611918c..87d621c47a7b 100644--- a/products/desktop/packages/core/src/inbox/reportVerdict.ts+++ b/products/desktop/packages/core/src/inbox/reportVerdict.ts@@ -66,7 +66,7 @@ export function deriveReportVerdict(return {tone: "decision",title: "Review the open PR",- body: "Implementation is already in flight. Review the pull request, or continue the work on its branch.",+ body: "Implementation is already in flight. Review the pull request, or continue the task that opened it — new work lands on the same branch.",};}if (report.already_addressed) {diff --git a/products/desktop/packages/core/src/sessions/sessionViewState.test.ts b/products/desktop/packages/core/src/sessions/sessionViewState.test.tsindex c40b0d91d858..a6a685fddb6a 100644--- a/products/desktop/packages/core/src/sessions/sessionViewState.test.ts+++ b/products/desktop/packages/core/src/sessions/sessionViewState.test.ts@@ -46,21 +46,6 @@ function makeSession(}describe("deriveSessionViewState", () => {- it("uses a live cloud session when task run metadata is unavailable", () => {- const task = makeTask("in_progress");- task.latest_run = undefined;-- const state = deriveSessionViewState(- makeSession("in_progress"),- task,- null,- false,- );-- expect(state.isCloud).toBe(true);- expect(state.isCloudRunNotTerminal).toBe(true);- });-it("uses terminal task status over stale same-run session status", () => {const state = deriveSessionViewState(makeSession("in_progress"),diff --git a/products/desktop/packages/shared/src/domain-types.ts b/products/desktop/packages/shared/src/domain-types.tsindex 6da0894f7d75..a0c82f38f1e8 100644--- a/products/desktop/packages/shared/src/domain-types.ts+++ b/products/desktop/packages/shared/src/domain-types.ts@@ -657,6 +657,12 @@ export interface SignalReport {source_products?: string[];/** PR URL from the latest implementation task run, if available. */implementation_pr_url?: string | null;+ /**+ * Whether that PR merged (GitHub webhook). A merged PR is history, not work+ * in flight: a report can outlive its fix when evidence keeps arriving, and+ * its old PR must not read as reviewable or continuable.+ */+ implementation_pr_merged?: boolean;/** Charts the report shows, placed by `[label](chart:<chart_id>)` links in the summary. */charts?: SignalReportChart[];/** The report's PR refund, when one exists (one refund per report, ever). */diff --git a/products/desktop/packages/shared/src/flags.ts b/products/desktop/packages/shared/src/flags.tsindex e42e37ca031d..ae8aa8b1a4a0 100644--- a/products/desktop/packages/shared/src/flags.ts+++ b/products/desktop/packages/shared/src/flags.ts@@ -68,6 +68,13 @@ export const SIGNALS_PR_REFUNDS_FLAG = "signals-pr-refunds";*/export const CHANNEL_REPORTS_FLAG = "posthog-desktop-channel-reports";+/**+ * The global reports inbox: one sectioned, keyboard-triageable page for every+ * report, reclaiming the inbox nav slot from the channel-reports takeover.+ * The per-space sidebar list stays the working set beside it.+ */+export const REPORTS_INBOX_FLAG = "posthog-desktop-reports-inbox";+/*** Serves a session's Claude traffic from Bedrock instead of Anthropic. The* `test` variant sends `x-posthog-provider: bedrock`, which the gateway routesdiff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelSidebar.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelSidebar.test.tsxindex bed8074e4387..a72287c67f6a 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelSidebar.test.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelSidebar.test.tsx@@ -49,36 +49,6 @@ vi.mock("@posthog/ui/features/canvas/components/ChannelsFab", () => ({// The row menu's spaces list reaches for a QueryClient the unit test has no// stack for. Stubbed at the module boundary, as ShellLayout.test.tsx does for// the same reason.-vi.mock("@posthog/ui/features/canvas/hooks/useChannelReports", () => ({- EMPTY_CHANNEL_REPORTS_FILTERS: {- search: "",- relevantToMeOnly: false,- priorities: [],- status: "all",- },- DEFAULT_CHANNEL_REPORTS_FILTERS: {- search: "",- relevantToMeOnly: true,- priorities: [],- status: "all",- },- useChannelReports: () => ({- reports: [],- statusCounts: {- all: 0,- "needs-review": 0,- ready: 0,- running: 0,- archived: 0,- },- hasReports: false,- isLoading: false,- isError: false,- fetchNextPage: () => {},- hasNextPage: false,- isFetchingNextPage: false,- }),-}));vi.mock("@posthog/ui/features/canvas/hooks/useChannels", () => ({useChannels: () => ({ channels: [] }),}));@@ -285,56 +255,6 @@ describe("ChannelSidebar", () => {);});- it("opens the report filter menu from the Reports tab header", async () => {- const user = userEvent.setup({ pointerEventsCheck: 0 });- mocks.channelReportsFlag = true;- mocks.pathname = "/website/channel-1/reports/report-9";- renderSidebar();-- await user.click(screen.getByRole("button", { name: "Filter reports" }));-- expect(await screen.findByText("For you")).toBeInTheDocument();- expect(screen.getByText("Needs review")).toBeInTheDocument();- expect(screen.getByText("P0")).toBeInTheDocument();- });-- it("cuts the sidebar over to Reports when a report opens", () => {- mocks.channelReportsFlag = true;- const { rerender } = renderSidebar();- expect(screen.getByRole("tab", { name: "Sessions" })).toHaveAttribute(- "aria-selected",- "true",- );-- mocks.pathname = "/website/channel-1/reports/report-9";- rerender(sidebar());-- expect(screen.getByRole("tab", { name: "Reports" })).toHaveAttribute(- "aria-selected",- "true",- );- });-- it("falls back to Sessions when the reports flag turns off on the Reports tab", () => {- mocks.channelReportsFlag = true;- mocks.pathname = "/website/channel-1/reports/report-9";- const { rerender } = renderSidebar();- expect(screen.getByRole("tab", { name: "Reports" })).toHaveAttribute(- "aria-selected",- "true",- );-- // A live flag rollback while parked on Reports must not strand the pane.- mocks.channelReportsFlag = false;- rerender(sidebar());-- expect(screen.queryByRole("tab", { name: "Reports" })).toBeNull();- expect(screen.getByRole("tab", { name: "Sessions" })).toHaveAttribute(- "aria-selected",- "true",- );- });-it("shows one kind at a time, and drops the run filters with the sessions", async () => {const user = userEvent.setup({ pointerEventsCheck: 0 });mocks.items = [diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelSidebar.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelSidebar.tsxindex c7971ded0865..0cb599d90ebc 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelSidebar.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelSidebar.tsx@@ -21,13 +21,7 @@ import {PINNED_SECTION_KEY,sortChannelItems,} from "@posthog/core/canvas/channelItems";-import { isGeneralChannel } from "@posthog/core/canvas/channelName";import { getCanvasCellId } from "@posthog/core/command-center/grid";-import {- channelReportView,- generalReportView,- type ReportChannelView,-} from "@posthog/core/inbox/reportChannelScope";import {Button,cn,@@ -51,21 +45,13 @@ import { ChannelBackRow } from "@posthog/ui/features/canvas/components/ChannelBaimport { ChannelFilterMenu } from "@posthog/ui/features/canvas/components/ChannelFilterMenu";import { ChannelItemDragPreview } from "@posthog/ui/features/canvas/components/ChannelItemDragPreview";import { ChannelItemRow } from "@posthog/ui/features/canvas/components/ChannelItemRow";-import { ChannelReportsSection } from "@posthog/ui/features/canvas/components/ChannelReportsSection";import { ChannelsFab } from "@posthog/ui/features/canvas/components/ChannelsFab";import { cnHeaderButton } from "@posthog/ui/features/canvas/components/channelHeaderButton";import {type ChannelPageKey,channelPageLabel,} from "@posthog/ui/features/canvas/components/channelPages";-import { ReportFilterControls } from "@posthog/ui/features/canvas/components/ReportFilterControls";import { useChannelItems } from "@posthog/ui/features/canvas/hooks/useChannelItems";-import {- type ChannelReportsFilters,- DEFAULT_CHANNEL_REPORTS_FILTERS,- EMPTY_CHANNEL_REPORTS_FILTERS,- useChannelReports,-} from "@posthog/ui/features/canvas/hooks/useChannelReports";import { useChannels } from "@posthog/ui/features/canvas/hooks/useChannels";import { useChannelTasksRunState } from "@posthog/ui/features/canvas/hooks/useChannelTasksRunState";import { useLocalDayStart } from "@posthog/ui/features/canvas/hooks/useLocalDayStart";@@ -75,7 +61,6 @@ import {placeCanvasInCommandCenter,placeTaskInCommandCenter,} from "@posthog/ui/features/command-center/placeTaskInCommandCenter";-import { useChannelReportsEnabled } from "@posthog/ui/features/feature-flags/useChannelReportsEnabled";import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";import { EditListItemAppearanceDialog } from "@posthog/ui/features/sidebar/components/EditListItemAppearanceDialog";import { SidebarKbdHint } from "@posthog/ui/features/sidebar/components/items/SidebarKbdHint";@@ -96,7 +81,6 @@ import { useNavigate, useRouterState } from "@tanstack/react-router";import { motion, useReducedMotion } from "framer-motion";import {Fragment,- type ReactNode,useCallback,useEffect,useMemo,@@ -129,12 +113,11 @@ function isInCommandCenter(}/** The list holds two kinds of thing, and shows one of them at a time. */-type ChannelTab = ChannelItemModel["kind"] | "report";+type ChannelTab = ChannelItemModel["kind"];const CHANNEL_TABS: readonly {value: ChannelTab;label: string;- badge?: boolean;}[] = [{ value: "task", label: "Sessions" },{ value: "canvas", label: "Canvases" },@@ -160,11 +143,9 @@ function RecentSectionHeader({showCreatedBy,showRunFilters,filtersActive,- showItemControls = true,- filterControls,}: {tab: ChannelTab;- tabs: readonly { value: ChannelTab; label: string; badge?: boolean }[];+ tabs: readonly { value: ChannelTab; label: string }[];onTabChange: (tab: ChannelTab) => void;searchOpen: boolean;onToggleSearch: () => void;@@ -187,20 +168,17 @@ function RecentSectionHeader({/** False on the canvases tab: a canvas has no run to ask these about. */showRunFilters: boolean;filtersActive: boolean;- /** False on the Reports tab, whose filters render via `filterControls`. */- showItemControls?: boolean;- /** Replaces the session/canvas filter menu (the Reports tab's controls). */- filterControls?: ReactNode;}) {- const hasControls = showItemControls || !!filterControls;return (<>- <div className="flex items-center gap-0.5">- {/* The tabs name the list, so it has no label of its own. */}+ <div className="flex flex-wrap items-center gap-0.5">+ {/* The tabs name the list, so it has no label of its own. Controls+ wrap under the tabs when the sidebar is narrow, so tab labels are+ never cut off. */}<Tabsvalue={tab}onValueChange={(value: string) => onTabChange(value as ChannelTab)}- className="min-w-0 flex-1"+ className="shrink-0">{/* text-[13px] is the sidebar's own scale: quill's default tab issized for a page header, which reads as a heading over this list. */}@@ -208,62 +186,47 @@ function RecentSectionHeader({can't be utilities here, see the rule's comment. */}<TabsListvariant="line"- className="quill-tabs-fill h-auto min-w-0 gap-0.5 overflow-hidden border-b-0"+ className="quill-tabs-fill h-auto gap-0.5 border-b-0">- {/* When space runs out, labels truncate instead of sliding under- the search button. The dot says the space has reports at all —- no counter — and only on an inactive tab, where the list isn't- already answering the question. */}- {tabs.map(({ value, label, badge }) => (+ {tabs.map(({ value, label }) => (<TabsTriggerkey={value}value={value}- className="min-w-0 rounded-sm px-1 py-0.5 text-[13px]"+ className="shrink-0 rounded-sm px-1 py-0.5 text-[13px]">- <span className="truncate">{label}</span>- {badge && value !== tab && (- <span- className="ml-1 size-1.5 shrink-0 rounded-full bg-(--amber-9)"- role="img"- aria-label="Has reports"- />- )}+ <span className="whitespace-nowrap">{label}</span></TabsTrigger>))}</TabsList></Tabs>- {hasControls && (- <>- <Button- variant="default"- size="icon-xs"- aria-label="Search"- aria-pressed={searchOpen}- onClick={onToggleSearch}- className={cnHeaderButton(searchOpen)}- >- <MagnifyingGlass size={12} />- </Button>- {filterControls ?? (- <ChannelFilterMenu- filters={filters}- onFilterChange={onFilterChange}- onClearFilters={onClearFilters}- sort={sort}- onSortChange={onSortChange}- grouping={grouping}- onGroupingChange={onGroupingChange}- onEditAppearance={onEditAppearance}- sources={sources}- showCreatedBy={showCreatedBy}- showRunFilters={showRunFilters}- active={filtersActive}- />- )}- </>- )}{" "}+ <>+ <Button+ variant="default"+ size="icon-xs"+ aria-label="Search"+ aria-pressed={searchOpen}+ onClick={onToggleSearch}+ className={cnHeaderButton(searchOpen)}+ >+ <MagnifyingGlass size={12} />+ </Button>+ <ChannelFilterMenu+ filters={filters}+ onFilterChange={onFilterChange}+ onClearFilters={onClearFilters}+ sort={sort}+ onSortChange={onSortChange}+ grouping={grouping}+ onGroupingChange={onGroupingChange}+ onEditAppearance={onEditAppearance}+ sources={sources}+ showCreatedBy={showCreatedBy}+ showRunFilters={showRunFilters}+ active={filtersActive}+ />+ </></div>- {hasControls && searchOpen && (+ {searchOpen && (<div className="px-1 pb-1"><InputautoFocus@@ -271,11 +234,7 @@ function RecentSectionHeader({onChange={(event) => onQueryChange(event.target.value)}placeholder="Search…"aria-label={- tab === "canvas"- ? "Search canvases"- : tab === "report"- ? "Search reports"- : "Search sessions"+ tab === "canvas" ? "Search canvases" : "Search sessions"}className="h-6 text-[12px]"/>@@ -376,7 +335,6 @@ export function ChannelSidebar({ channelId }: { channelId: string }) {const navigate = useNavigate();const pathname = useRouterState({ select: (s) => s.location.pathname });const loopsEnabled = useFeatureFlag(LOOPS_FLAG, import.meta.env.DEV);- const reportsEnabled = useChannelReportsEnabled();const { items, actions, me, isLoading, channelMissing } =useChannelItems(channelId);@@ -394,16 +352,10 @@ export function ChannelSidebar({ channelId }: { channelId: string }) {channelId,tab: "task" as ChannelTab,});- const chosen = chosenTab.channelId === channelId ? chosenTab.tab : "task";- // A live flag rollback can leave "report" selected; fall back to sessions so- // the reports pane can't outlive the flag that gates it.- const tab = chosen === "report" && !reportsEnabled ? "task" : chosen;+ const tab = chosenTab.channelId === channelId ? chosenTab.tab : "task";const setTab = (next: ChannelTab) => setChosenTab({ channelId, tab: next });const [searchOpen, setSearchOpen] = useState(false);const [query, setQuery] = useState("");- const [reportFilters, setReportFilters] = useState<ChannelReportsFilters>(- DEFAULT_CHANNEL_REPORTS_FILTERS,- );const [rawFilters, setFilters] = useState<ChannelItemFilters>(DEFAULT_CHANNEL_ITEM_FILTERS,);@@ -434,35 +386,7 @@ export function ChannelSidebar({ channelId }: { channelId: string }) {// so its name is no longer the backend's.const channel = channels.find((c) => c.id === channelId);const isPersonalChannel = channel?.channelType === "personal";- // The general space is the reports catch-all: it lists every report, while any- // other space lists only reports assigned to it.- const reportView: ReportChannelView =- channel &&- !isGeneralChannel({ channel_type: channel.channelType, name: channel.name })- ? channelReportView(channelId)- : generalReportView();- // Shares the section's query key, so the dot costs no extra fetch.- const { hasReports } = useChannelReports(- reportView,- EMPTY_CHANNEL_REPORTS_FILTERS,- { enabled: reportsEnabled },- );- const visibleTabs = useMemo(- () =>- reportsEnabled- ? [- // Reports lead: they arrive on their own and carry the dot, so- // they take the first slot; the space still opens on its sessions.- {- value: "report" as ChannelTab,- label: "Reports",- badge: hasReports,- },- ...CHANNEL_TABS,- ]- : CHANNEL_TABS,- [reportsEnabled, hasReports],- );+ const visibleTabs = CHANNEL_TABS;// The tab is the list, so everything below it — the filters, the empty state,// the sections — is about one kind of thing at a time.const tabItems = useMemo(@@ -512,20 +436,6 @@ export function ChannelSidebar({ channelId }: { channelId: string }) {const task = pathname.match(/\/tasks\/([^/]+)$/);return task ? `task:${task[1]}` : null;}, [pathname]);- const activeReportId = useMemo(() => {- const match = pathname.match(- /\/(?:inbox\/(?:reports|pulls|dismissed)|website\/[^/]+\/reports)\/([^/]+)$/,- );- return match ? match[1] : null;- }, [pathname]);-- // Opening a report (feed card, deep link, old inbox link) cuts the sidebar- // over to Reports so the open report shows highlighted in its list. Only on- // report change — the user can still switch tabs while the report stays open.- useEffect(() => {- if (!reportsEnabled || !activeReportId) return;- setChosenTab({ channelId, tab: "report" });- }, [reportsEnabled, activeReportId, channelId]);// Pins sort to the top because a pin is a request not to lose the thing:// below the chosen order it would fall off the end of the cap. The cap is@@ -852,50 +762,7 @@ export function ChannelSidebar({ channelId }: { channelId: string }) {ref={listAnchorRef}className="relative mt-2 flex min-h-0 flex-1 flex-col">- {tab === "report" && (- <>- <div className="border-border border-b px-2">- <RecentSectionHeader- tab={tab}- tabs={visibleTabs}- onTabChange={setTab}- showItemControls={false}- grouping={grouping}- onGroupingChange={changeGrouping}- onEditAppearance={() => setAppearanceOpen(true)}- filterControls={- <ReportFilterControls- filters={reportFilters}- onChange={setReportFilters}- compact- />- }- searchOpen={searchOpen}- onToggleSearch={() => {- if (searchOpen) setQuery("");- setSearchOpen(!searchOpen);- }}- query={query}- onQueryChange={setQuery}- filters={filters}- onFilterChange={() => {}}- onClearFilters={() => {}}- sort={sort}- onSortChange={() => {}}- sources={sources}- showCreatedBy={false}- showRunFilters={false}- filtersActive={false}- />- </div>- <ChannelReportsSection- view={reportView}- activeReportId={activeReportId}- filters={{ ...reportFilters, search: query }}- />- </>- )}- {tab !== "report" && showHeader && (+ {showHeader && (<div className="border-border border-b px-2"><RecentSectionHeadertab={tab}@@ -930,80 +797,74 @@ export function ChannelSidebar({ channelId }: { channelId: string }) {)}{/* Pin and unpin stay reachable from the row's menu and its contextmenu, so the drag adds no keyboard-only path. */}- {tab !== "report" && (- <>- {/* biome-ignore lint/a11y/noStaticElementInteractions: drag-and-drop container */}- <div- aria-busy={isLoading}- className="scroll-mask-4 min-h-0 flex-1 overflow-y-auto px-2 pt-1 pb-2"- onDragOver={pinDrag.listProps.onDragOver}- onDrop={pinDrag.listProps.onDrop}- >- {listState === "loading" && <ChannelItemsSkeleton />}+ <>+ {/* biome-ignore lint/a11y/noStaticElementInteractions: drag-and-drop container */}+ <div+ aria-busy={isLoading}+ className="scroll-mask-4 min-h-0 flex-1 overflow-y-auto px-2 pt-1 pb-2"+ onDragOver={pinDrag.listProps.onDragOver}+ onDrop={pinDrag.listProps.onDrop}+ >+ {listState === "loading" && <ChannelItemsSkeleton />}++ {listState === "unavailable" && (+ <Empty className="border-0 py-6">+ <EmptyHeader>+ <EmptyMedia variant="icon">+ <PackageIcon size={18} />+ </EmptyMedia>+ <EmptyTitle>Space unavailable</EmptyTitle>+ <EmptyDescription>+ It may have been deleted, or belong to another project.+ </EmptyDescription>+ </EmptyHeader>+ </Empty>+ )}- {listState === "unavailable" && (+ {showHeader &&+ (listState === "empty" ? (+ <TabEmptyState tab={tab} />+ ) : sections.length > 0 ? (+ <div className="flex flex-col gap-px">+ {/* Always mounted, empty or not. Inserting the run on+ dragstart restructures the list under the dragged row, and+ Chromium ends the drag on the spot: dragstart, then dragend,+ before the pointer moves. Growing one already there is+ fine. */}+ {pinnedRun()}+ {datedSections.map((section) => (+ <Fragment key={section.key}>+ {section.label && <MenuLabel>{section.label}</MenuLabel>}+ {section.items.map((item) => taskRow(item, true))}+ </Fragment>+ ))}+ </div>+ ) : (<Empty className="border-0 py-6"><EmptyHeader><EmptyMedia variant="icon">- <PackageIcon size={18} />+ <MagnifyingGlass size={18} /></EmptyMedia>- <EmptyTitle>Space unavailable</EmptyTitle>+ <EmptyTitle>No matches</EmptyTitle><EmptyDescription>- It may have been deleted, or belong to another project.+ Try a different search or clear the filters.</EmptyDescription></EmptyHeader></Empty>- )}-- {showHeader &&- (listState === "empty" ? (- <TabEmptyState tab={tab} />- ) : sections.length > 0 ? (- <div className="flex flex-col gap-px">- {/* Always mounted, empty or not. Inserting the run on- dragstart restructures the list under the dragged row, and- Chromium ends the drag on the spot: dragstart, then dragend,- before the pointer moves. Growing one already there is- fine. */}- {pinnedRun()}- {datedSections.map((section) => (- <Fragment key={section.key}>- {section.label && (- <MenuLabel>{section.label}</MenuLabel>- )}- {section.items.map((item) => taskRow(item, true))}- </Fragment>- ))}- </div>- ) : (- <Empty className="border-0 py-6">- <EmptyHeader>- <EmptyMedia variant="icon">- <MagnifyingGlass size={18} />- </EmptyMedia>- <EmptyTitle>No matches</EmptyTitle>- <EmptyDescription>- Try a different search or clear the filters.- </EmptyDescription>- </EmptyHeader>- </Empty>- ))}- </div>- <ChannelsFab channelId={channelId} />- <MarqueeOverlay rect={marquee} />- </>- )}+ ))}+ </div>+ <ChannelsFab channelId={channelId} />+ <MarqueeOverlay rect={marquee} />+ </></div>{/* Below the list rather than floating over it: the bottom rows are wherea shift-click range usually ends, and the FAB already sits there. */}- {tab !== "report" && (- <SidebarBulkActionBar- actions={bulkActions}- onClearSelection={clearSelection}- onArchive={archiveConfirm.requestArchive}- />- )}+ <SidebarBulkActionBar+ actions={bulkActions}+ onClearSelection={clearSelection}+ onArchive={archiveConfirm.requestArchive}+ />{archiveConfirm.dialog}{pinDrag.drag ? (diff --git a/products/desktop/packages/ui/src/features/canvas/components/ReportFeedRow.tsx b/products/desktop/packages/ui/src/features/canvas/components/ReportFeedRow.tsxindex a7dec7c5941b..236065ddaf67 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ReportFeedRow.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ReportFeedRow.tsx@@ -12,7 +12,6 @@ import {ReportStateMonogram,reportRunState,} from "@posthog/ui/features/inbox/components/ReportStateMonogram";-import { ForYouBadge } from "@posthog/ui/features/inbox/components/utils/ForYouBadge";import { InboxBadge } from "@posthog/ui/features/inbox/components/utils/InboxBadge";import { useInboxReportDismissAction } from "@posthog/ui/features/inbox/hooks/useInboxReportDismissAction";import { useMemo } from "react";@@ -55,7 +54,6 @@ export function ReportFeedRow({<span className="min-w-0 truncate font-semibold text-sm leading-snug">{title}</span>- {report.is_suggested_reviewer && <ForYouBadge />}{report.implementation_pr_url && (<GitPullRequestIconsize={13}diff --git a/products/desktop/packages/ui/src/features/feature-flags/useReportsInboxEnabled.ts b/products/desktop/packages/ui/src/features/feature-flags/useReportsInboxEnabled.tsnew file mode 100644index 000000000000..90976a3c3749--- /dev/null+++ b/products/desktop/packages/ui/src/features/feature-flags/useReportsInboxEnabled.ts@@ -0,0 +1,11 @@+import { REPORTS_INBOX_FLAG } from "@posthog/shared";+import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";++/**+ * Whether the global reports inbox owns the inbox nav slot. One hook so the+ * page takeover and the nav entries flip together. Defaults on in dev builds,+ * same as channel reports.+ */+export function useReportsInboxEnabled(): boolean {+ return useFeatureFlag(REPORTS_INBOX_FLAG, import.meta.env.DEV);+}diff --git a/products/desktop/packages/ui/src/features/inbox/components/InboxDetailFrame.tsx b/products/desktop/packages/ui/src/features/inbox/components/InboxDetailFrame.tsxindex fcc5cbdb5ee7..d9462c525328 100644--- a/products/desktop/packages/ui/src/features/inbox/components/InboxDetailFrame.tsx+++ b/products/desktop/packages/ui/src/features/inbox/components/InboxDetailFrame.tsx@@ -1,6 +1,7 @@import type { IconProps } from "@phosphor-icons/react";import { extractRepoSelectionRepository } from "@posthog/core/inbox/artefacts";import { renderableReportChartIds } from "@posthog/core/inbox/reportCharts";+import { splitReportSummary } from "@posthog/core/inbox/reportPresentation";import {Tabs,TabsList,@@ -35,7 +36,7 @@ import {useInboxReportSignals,} from "@posthog/ui/features/inbox/hooks/useInboxReports";import { RelativeTimestamp } from "@posthog/ui/primitives/RelativeTimestamp";-import { type ComponentType, type ReactNode, useState } from "react";+import { type ComponentType, type ReactNode, useMemo, useState } from "react";interface InboxDetailFrameProps {report: SignalReport;@@ -242,27 +243,11 @@ export function InboxDetailFrame({<div className="grid @4xl:grid-cols-[minmax(0,80ch)_minmax(0,1fr)] grid-cols-1 gap-5"><div className="flex min-w-0 flex-col gap-5">{aboveSummary}- <DetailSection+ <ReportSummarySlots+ report={report}+ fallbackTitle={summarySection.title}Icon={SummaryIcon}- title={summarySection.title}- collapsible- >- <SignalReportSummaryMarkdown- content={report.summary}- fallback="No summary yet. The agent is still investigating."- variant="detail"- pending={report.status === "in_progress"}- chartIds={renderableReportChartIds(report.charts)}- />- {report.charts && report.charts.length > 0 && (- <div className="mt-4">- <ReportChartsSection- reportId={report.id}- charts={report.charts}- />- </div>- )}- </DetailSection>+ />{belowSummary}</div>@@ -296,3 +281,86 @@ export function InboxDetailFrame({</div>);}++/**+ * The summary rendered as labeled slots instead of one wall of prose: the+ * lede (the summary's own tl;dr) stays above the fold, the first section+ * opens by default, and the rest sit behind disclosure. Nothing is cut —+ * the reader jumps to the slot they need instead of reading linearly.+ * Heading-less summaries render whole, exactly as before.+ */+function ReportSummarySlots({+ report,+ fallbackTitle,+ Icon,+}: {+ report: SignalReport;+ fallbackTitle: string;+ Icon: ComponentType<IconProps>;+}) {+ const split = useMemo(+ () => splitReportSummary(report.summary),+ [report.summary],+ );+ const chartIds = renderableReportChartIds(report.charts);+ const charts = report.charts && report.charts.length > 0 && (+ <div className="mt-4">+ <ReportChartsSection reportId={report.id} charts={report.charts} />+ </div>+ );++ if (split.sections.length === 0) {+ return (+ <DetailSection Icon={Icon} title={fallbackTitle} collapsible>+ <SignalReportSummaryMarkdown+ content={report.summary}+ fallback="No summary yet. The agent is still investigating."+ variant="detail"+ pending={report.status === "in_progress"}+ chartIds={chartIds}+ />+ {charts}+ </DetailSection>+ );+ }++ return (+ <>+ {split.lede && (+ <DetailSection Icon={Icon} title={fallbackTitle}>+ <SignalReportSummaryMarkdown+ content={split.lede}+ fallback=""+ variant="detail"+ pending={report.status === "in_progress"}+ chartIds={chartIds}+ />+ </DetailSection>+ )}+ {split.sections.map((section, index) => (+ <DetailSection+ key={`${section.title}-${index}`}+ Icon={Icon}+ title={section.title}+ collapsible+ defaultCollapsed={index > 0}+ >+ <SignalReportSummaryMarkdown+ content={section.body}+ fallback=""+ variant="detail"+ pending={false}+ chartIds={chartIds}+ />+ </DetailSection>+ ))}+ {/* Charts stay outside the collapsibles: in-prose chart links jump to+ these anchors, and a jump into a folded section lands nowhere. */}+ {report.charts && report.charts.length > 0 && (+ <DetailSection Icon={Icon} title="Charts">+ <ReportChartsSection reportId={report.id} charts={report.charts} />+ </DetailSection>+ )}+ </>+ );+}diff --git a/products/desktop/packages/ui/src/features/inbox/components/InboxView.tsx b/products/desktop/packages/ui/src/features/inbox/components/InboxView.tsxindex 970993c0d8a7..dd0c75306ef3 100644--- a/products/desktop/packages/ui/src/features/inbox/components/InboxView.tsx+++ b/products/desktop/packages/ui/src/features/inbox/components/InboxView.tsx@@ -1,7 +1,9 @@import { EnvelopeSimpleIcon } from "@phosphor-icons/react";import { isInboxDetailPath } from "@posthog/core/inbox/reportMembership";import { useChannelReportsEnabled } from "@posthog/ui/features/feature-flags/useChannelReportsEnabled";+import { useReportsInboxEnabled } from "@posthog/ui/features/feature-flags/useReportsInboxEnabled";import { InboxPageHeader } from "@posthog/ui/features/inbox/components/InboxPageHeader";+import { ReportsInboxView } from "@posthog/ui/features/inbox/components/ReportsInboxView";import { useInboxAllReports } from "@posthog/ui/features/inbox/hooks/useInboxAllReports";import { resetReportOpenTrackerHistory } from "@posthog/ui/features/inbox/hooks/useReportOpenTracker";import { useTrackInboxViewed } from "@posthog/ui/features/inbox/hooks/useTrackInboxViewed";@@ -45,12 +47,27 @@ export function InboxView() {const pathname = useRouterState({ select: (s) => s.location.pathname });const isDetailView = isInboxDetailPath(pathname);+ const channelReportsEnabled = useChannelReportsEnabled();+ // The global reports inbox replaces the pipeline tabs with one sectioned,+ // keyboard-triageable page, and reclaims the inbox slot from the spaces+ // redirect below. Detail routes keep their own bodies.+ const reportsInboxEnabled = useReportsInboxEnabled();++ if (reportsInboxEnabled && !isDetailView) {+ return (+ <Flex direction="column" className="h-full min-h-0">+ <div className="min-h-0 flex-1 overflow-auto">+ <ReportsInboxView />+ </div>+ </Flex>+ );+ }+// With channel reports on, spaces replace the inbox as the home for reports.// List tabs reached through stale history or bookmarks land on the spaces// index; detail URLs keep working (deep links and old history still carry// them, and the in-space route can't be derived from a bare report URL here).- const channelReportsEnabled = useChannelReportsEnabled();- if (channelReportsEnabled && !isDetailView) {+ if (channelReportsEnabled && !reportsInboxEnabled && !isDetailView) {return <Navigate replace to="/website" />;}diff --git a/products/desktop/packages/ui/src/features/inbox/components/ReportChatSidebar.tsx b/products/desktop/packages/ui/src/features/inbox/components/ReportChatSidebar.tsxindex c8d571deff09..ed69bb09942d 100644--- a/products/desktop/packages/ui/src/features/inbox/components/ReportChatSidebar.tsx+++ b/products/desktop/packages/ui/src/features/inbox/components/ReportChatSidebar.tsx@@ -165,6 +165,7 @@ function ReportChatStarter({ report }: { report: SignalReport }) {const setStarterDraft = useReportChatPanelStore((s) => s.setStarterDraft);const clearStarterDraft = useReportChatPanelStore((s) => s.clearStarterDraft);+ // Taken atomically so a double-fired effect can't paste the quote twice.useEffect(() => {if (!pendingQuote) return;const current =@@ -212,6 +213,18 @@ function ReportChatStarter({ report }: { report: SignalReport }) {void discussReport(trimmed);}, [starterDraft, isDiscussing, discussReport, fireAction]);+ // Canned starter prompts go through the same privacy-safe path as submit:+ // the analytics event records that a question was asked, never its text.+ const ask = useCallback(+ (text: string) => {+ const trimmed = text.trim();+ if (!trimmed || isDiscussing) return;+ fireAction("discuss", { has_question: true });+ void discussReport(trimmed);+ },+ [isDiscussing, discussReport, fireAction],+ );+return (<div className="flex h-full flex-col justify-between gap-3 p-3"><div className="flex flex-col gap-1 pt-1">@@ -222,6 +235,27 @@ function ReportChatStarter({ report }: { report: SignalReport }) {The agent joins with the full report and its evidence already incontext. Highlight any part of the report to quote it here.</span>+ <div className="mt-1 flex flex-wrap gap-1.5">+ {[+ "What caused this?",+ "Who is affected?",+ "Walk me through the fix",+ ].map((prompt) => (+ <Button+ key={prompt}+ type="button"+ variant="outline"+ size="sm"+ // Once the composer holds a typed draft or a quoted passage, the+ // one-click chips step aside — firing a chip must not silently+ // discard what the user wrote or highlighted.+ disabled={isDiscussing || starterDraft.trim().length > 0}+ onClick={() => ask(prompt)}+ >+ {prompt}+ </Button>+ ))}+ </div></div><formclassName="flex flex-col gap-2"diff --git a/products/desktop/packages/ui/src/features/inbox/components/ReportDetailActions.tsx b/products/desktop/packages/ui/src/features/inbox/components/ReportDetailActions.tsxindex 143097f94dae..c29a800c4bf9 100644--- a/products/desktop/packages/ui/src/features/inbox/components/ReportDetailActions.tsx+++ b/products/desktop/packages/ui/src/features/inbox/components/ReportDetailActions.tsx@@ -157,7 +157,7 @@ export function ReportDetailActions({title="Chat with the agent about this report"><ChatCircleIcon size={12} />- Discuss+ Chat with this report</Button>{canvasActionEnabled && (@@ -179,7 +179,7 @@ export function ReportDetailActions({title="Have the agent build a canvas from this report">{isCreatingCanvas ? <Spinner /> : <ShapesIcon size={12} />}- Canvas+ Create canvas…</Button>}/>@@ -225,7 +225,22 @@ export function ReportDetailActions({</Popover>)}- {overflowMenu}+ {/* An overflow menu earns its click only with something to hide; when+ Copy link is the lone occasional action, it shows directly. */}+ {!prUrl && !refund.canRefund ? (+ <Button+ type="button"+ variant="outline"+ size="sm"+ aria-label="Copy link to this report"+ title="Copy link to this report"+ onClick={() => copyInboxReportLink(report)}+ >+ <CopyIcon size={13} />+ </Button>+ ) : (+ overflowMenu+ )}{refund.canRefund && (<RefundReportDialogdiff --git a/products/desktop/packages/ui/src/features/inbox/components/ReportVerdictBanner.tsx b/products/desktop/packages/ui/src/features/inbox/components/ReportVerdictBanner.tsxindex 1dc4023a3a5e..2d5c47b0fe73 100644--- a/products/desktop/packages/ui/src/features/inbox/components/ReportVerdictBanner.tsx+++ b/products/desktop/packages/ui/src/features/inbox/components/ReportVerdictBanner.tsx@@ -1,4 +1,8 @@-import { ArrowSquareOutIcon, GitPullRequestIcon } from "@phosphor-icons/react";+import {+ ArchiveIcon,+ ArrowSquareOutIcon,+ GitPullRequestIcon,+} from "@phosphor-icons/react";import { extractRepoSelectionRepository } from "@posthog/core/inbox/artefacts";import { canCreateImplementationPr } from "@posthog/core/inbox/reportActions";import {@@ -16,6 +20,7 @@ import {} from "@posthog/quill";import type { SignalReport } from "@posthog/shared/types";import { useCreatePrReport } from "@posthog/ui/features/inbox/hooks/useCreatePrReport";+import { useInboxReportDismissAction } from "@posthog/ui/features/inbox/hooks/useInboxReportDismissAction";import { useInboxReportArtefacts } from "@posthog/ui/features/inbox/hooks/useInboxReports";import { useReportActionTracker } from "@posthog/ui/features/inbox/hooks/useReportActionTracker";import {@@ -66,9 +71,14 @@ export function ReportVerdictBanner({ report }: ReportVerdictBannerProps) {report.status,);const continuableTask = findContinuableImplementationTask(reportTasks);+ // A merged PR is history, not live work: the report only still exists+ // because evidence kept arriving after the fix, so it reads by its own+ // state (usually "needs your decision" again) rather than "review the PR".+ const livePrUrl = report.implementation_pr_merged+ ? null+ : report.implementation_pr_url;const existingPrUrl =- report.implementation_pr_url ??- (continuableTask ? getTaskPrUrl(continuableTask) : null);+ livePrUrl ?? (continuableTask ? getTaskPrUrl(continuableTask) : null);const hasExistingPr = !!existingPrUrl || !!continuableTask;const verdict = deriveReportVerdict(report, { hasExistingPr });@@ -85,6 +95,18 @@ export function ReportVerdictBanner({ report }: ReportVerdictBannerProps) {const [prOpen, setPrOpen] = useState(false);const [prFeedback, setPrFeedback] = useState("");+ // Archive is the "no" beside Create PR's "yes" — a decision, so it lives in+ // the decision row. Offered wherever the report is waiting on a person+ // (several verdict bodies tell the reader to archive; the button should be+ // right there). Running reports keep it out of the banner — the header's+ // Dismiss covers that rare case.+ const { dialog: dismissDialog, openDialog: openDismissDialog } =+ useInboxReportDismissAction(report);+ const canArchiveHere =+ report.status === "ready" ||+ report.status === "failed" ||+ report.status === "pending_input";+const handleCreatePr = useCallback(() => {const trimmed = prFeedback.trim();fireAction("create_pr", {@@ -130,7 +152,7 @@ export function ReportVerdictBanner({ report }: ReportVerdictBannerProps) {{showActions && (<div className="flex flex-wrap items-center gap-2.5">- {hasExistingPr ? (+ {report.status === "ready" && hasExistingPr ? (<><Buttontype="button"@@ -144,7 +166,7 @@ export function ReportVerdictBanner({ report }: ReportVerdictBannerProps) {) : (<GitPullRequestIcon size={15} />)}- Continue existing PR+ Continue the task</Button>{existingPrUrl && (<a@@ -158,7 +180,7 @@ export function ReportVerdictBanner({ report }: ReportVerdictBannerProps) {</a>)}</>- ) : (+ ) : report.status === "ready" && canCreatePr ? (<Popoveropen={prOpen}onOpenChange={(next) => {@@ -222,9 +244,21 @@ export function ReportVerdictBanner({ report }: ReportVerdictBannerProps) {</div></PopoverContent></Popover>+ ) : null}+ {canArchiveHere && (+ <Button+ type="button"+ variant="outline"+ onClick={openDismissDialog}+ className={BIG_BUTTON}+ >+ <ArchiveIcon size={15} />+ Archive…+ </Button>)}</div>)}+ {dismissDialog}</div>);}diff --git a/products/desktop/packages/ui/src/features/inbox/components/ReportsInboxView.tsx b/products/desktop/packages/ui/src/features/inbox/components/ReportsInboxView.tsxnew file mode 100644index 000000000000..a4a87e4c35d7--- /dev/null+++ b/products/desktop/packages/ui/src/features/inbox/components/ReportsInboxView.tsx@@ -0,0 +1,413 @@+import {+ CaretDownIcon,+ EnvelopeSimpleIcon,+ GitPullRequestIcon,+} from "@phosphor-icons/react";+import { humanizeIdentifier } from "@posthog/core/inbox/activityLog";+import {+ INBOX_DISMISSED_STATUS_FILTER,+ REPORTS_INBOX_STATUS_FILTER,+} from "@posthog/core/inbox/reportFiltering";+import { partitionInboxReports } from "@posthog/core/inbox/reportInboxSections";+import {+ deriveHeadline,+ humanizeReportTitle,+ parsePrUrl,+} from "@posthog/core/inbox/reportPresentation";+import {+ Button,+ Empty,+ EmptyDescription,+ EmptyHeader,+ EmptyMedia,+ EmptyTitle,+ Skeleton,+ Spinner,+} from "@posthog/quill";+import type { SignalReport } from "@posthog/shared/types";+import { InboxScopeSelect } from "@posthog/ui/features/inbox/components/InboxScopeSelect";+import { InboxSearchFilterBar } from "@posthog/ui/features/inbox/components/InboxSearchFilterBar";+import { SuggestedReviewerAvatarStack } from "@posthog/ui/features/inbox/components/SuggestedReviewerAvatarStack";+import { SignalReportPriorityBadge } from "@posthog/ui/features/inbox/components/utils/SignalReportPriorityBadge";+import { useInboxAllReports } from "@posthog/ui/features/inbox/hooks/useInboxAllReports";+import { useInboxReportDismissAction } from "@posthog/ui/features/inbox/hooks/useInboxReportDismissAction";+import { useInboxReportsInfinite } from "@posthog/ui/features/inbox/hooks/useInboxReports";+import { useInboxSectionCounts } from "@posthog/ui/features/inbox/hooks/useInboxSectionCounts";+import { RelativeTimestamp } from "@posthog/ui/primitives/RelativeTimestamp";+import {+ navigateToAgents,+ navigateToInboxReportDetail,+} from "@posthog/ui/router/navigationBridge";+import { openExternalUrl } from "@posthog/ui/shell/openExternal";+import { useEffect, useMemo, useState } from "react";++/** Rows shown per section before "Show more" — a scan, not a scroll. */+const SECTION_PREVIEW_LIMIT = 5;++/**+ * How many reports auto-paging will load before stopping and marking counts+ * incomplete ("+"). Bounds the page's cost on enormous projects while keeping+ * counts exact for realistic scoped populations.+ */+const AUTOPAGE_REPORT_LIMIT = 400;++/**+ * The global reports inbox: every report in the project on one page,+ * sectioned by what it asks (a decision, or just watching), quantified by the+ * evidence behind it, and triageable one at a time in focus mode. The+ * per-space sidebar list stays the working set; this is everything else.+ */+export function ReportsInboxView() {+ const {+ scopedReports,+ allReports,+ isLoading,+ hasNextPage,+ isFetchingNextPage,+ fetchNextPage,+ searchQuery,+ } = useInboxAllReports({ statusFilter: REPORTS_INBOX_STATUS_FILTER });++ const sections = useMemo(+ () => partitionInboxReports(scopedReports),+ [scopedReports],+ );+ // Section totals are server-side count queries — at this dataset's size the+ // loaded rows are always a window, so nothing user-facing counts them.+ // Search is the one exception: it's a client-side title match, so a+ // searching page counts its matching rows instead.+ const serverCounts = useInboxSectionCounts();+ const searchActive = searchQuery.trim().length > 0;+ const decisionCount = searchActive+ ? sections.decision.length+ : serverCounts.decision;+ const monitoringCount = searchActive+ ? sections.monitoring.length+ : serverCounts.monitoring;++ // Keep paging rows in (capped) so the sections have bodies to render —+ // counts never depend on this; they come from the server queries above.+ useEffect(() => {+ if (+ !hasNextPage ||+ isFetchingNextPage ||+ isLoading ||+ // Bound on rows actually loaded, not on search matches: a narrow+ // search shrinks scopedReports and would otherwise page far past the cap.+ allReports.length >= AUTOPAGE_REPORT_LIMIT+ ) {+ return;+ }+ fetchNextPage();+ }, [+ hasNextPage,+ isFetchingNextPage,+ isLoading,+ allReports.length,+ fetchNextPage,+ ]);++ const isEmpty = searchActive+ ? sections.decision.length === 0 && sections.monitoring.length === 0+ : !serverCounts.isLoading &&+ serverCounts.decision === 0 &&+ serverCounts.monitoring === 0;++ return (+ <div className="mx-auto flex w-full max-w-3xl flex-col gap-4 px-6 py-4">+ <div className="flex flex-wrap items-start justify-between gap-3">+ <div className="flex flex-col gap-0.5">+ <h1 className="font-semibold text-[15px] text-gray-12">Inbox</h1>+ <p className="text-[12.5px] text-gray-11">+ Issues and opportunities found in your product, ready to review+ </p>+ </div>+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={() => navigateToAgents()}+ >+ Configure agents+ </Button>+ </div>++ <div className="flex flex-wrap items-center justify-end gap-2">+ <div className="flex items-center gap-2">+ <InboxScopeSelect />+ </div>+ </div>++ <InboxSearchFilterBar searchPlaceholder="Search reports…" />++ {isLoading && scopedReports.length === 0 ? (+ <div aria-hidden className="flex flex-col gap-2 pt-2">+ {[70, 55, 80, 60].map((width) => (+ <div key={width} className="flex items-center gap-3 py-2">+ <Skeleton className="h-4" style={{ width: `${width}%` }} />+ </div>+ ))}+ </div>+ ) : isEmpty ? (+ <Empty className="mx-auto max-w-md py-16">+ <EmptyHeader>+ <EmptyMedia variant="icon">+ <EnvelopeSimpleIcon size={24} />+ </EmptyMedia>+ <EmptyTitle>Nothing to review</EmptyTitle>+ <EmptyDescription>+ Reports show up here as your agents find things worth acting on.+ </EmptyDescription>+ </EmptyHeader>+ </Empty>+ ) : (+ <>+ <InboxSection+ title="Needs a decision"+ reports={sections.decision}+ count={decisionCount}+ caption={+ !searchActive && serverCounts.decisionPr > 0+ ? `${serverCounts.decisionPr} with a PR to review`+ : undefined+ }+ emptyNote="Nothing waiting on you."+ />+ <InboxSection+ title="Monitoring"+ reports={sections.monitoring}+ count={monitoringCount}+ />+ <ResolvedSection />+ {isFetchingNextPage && (+ <div className="flex justify-center py-2">+ <Spinner />+ </div>+ )}+ </>+ )}+ </div>+ );+}++// A section header + capped rows. "Needs a decision" renders even when empty+// (the page's whole question deserves an explicit answer); others only with+// content.+function InboxSection({+ title,+ reports,+ count,+ caption,+ emptyNote,+}: {+ title: string;+ /** The loaded rows to render — a window; never what the header counts. */+ reports: SignalReport[];+ /** The section's true total, from a server-side count query. */+ count: number;+ /** Secondary breakdown shown after the count (e.g. "37 with a PR to review"). */+ caption?: string;+ emptyNote?: string;+}) {+ const [expanded, setExpanded] = useState(false);+ if (count === 0 && reports.length === 0 && !emptyNote) return null;+ const visible = expanded ? reports : reports.slice(0, SECTION_PREVIEW_LIMIT);+ const hidden = reports.length - visible.length;+ return (+ <section className="flex flex-col gap-1.5">+ <h2 className="flex items-baseline gap-2 border-(--gray-5) border-b pb-1 font-medium text-[11px] text-gray-10 uppercase tracking-wide">+ {title}+ <span className="tabular-nums">({count})</span>+ {caption && (+ <span className="font-normal normal-case tracking-normal">+ · {caption}+ </span>+ )}+ </h2>+ {count === 0 && reports.length === 0 ? (+ <p className="px-1 py-2 text-[12.5px] text-gray-10">{emptyNote}</p>+ ) : (+ <div className="flex flex-col gap-1">+ {visible.map((report) => (+ <InboxReportRow key={report.id} report={report} />+ ))}+ {hidden > 0 && (+ <Button+ type="button"+ variant="link-muted"+ size="sm"+ className="self-center text-gray-10"+ onClick={() => setExpanded(true)}+ >+ Show more ({hidden})+ </Button>+ )}+ </div>+ )}+ </section>+ );+}++// A row carries what the old inbox's cards proved useful: the humanized+// title, one line of the summary's tl;dr (deciding without opening), where it+// came from, reviewers, the PR when there is one, and archive on hover — at+// row density rather than card height.+function InboxReportRow({ report }: { report: SignalReport }) {+ const products = (report.source_products ?? [])+ .map((product) => humanizeIdentifier(product).toLowerCase())+ .join(" · ");+ const headline = useMemo(+ () => deriveHeadline(report.summary),+ [report.summary],+ );+ const pr = report.implementation_pr_url+ ? parsePrUrl(report.implementation_pr_url)+ : null;+ const { actionButton: archiveButton, dialog: archiveDialog } =+ useInboxReportDismissAction(report);+ return (+ <>+ {/* biome-ignore lint/a11y/useSemanticElements: the row holds a real archive <button>, which a <button> row would illegally nest */}+ <div+ role="button"+ tabIndex={0}+ onClick={() => navigateToInboxReportDetail(report.id)}+ onKeyDown={(event) => {+ if (event.key === "Enter" || event.key === " ") {+ event.preventDefault();+ navigateToInboxReportDetail(report.id);+ }+ }}+ className="group flex w-full cursor-pointer items-center gap-3 rounded-(--radius-2) border border-border bg-(--color-panel-solid) px-3 py-2 text-left transition hover:border-(--gray-6) hover:bg-(--gray-2)"+ >+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">+ <span className="flex items-center gap-1.5">+ <span className="truncate font-medium text-[13px] text-gray-12">+ {humanizeReportTitle(report.title, "Untitled report")}+ </span>+ </span>+ {headline && (+ <span className="line-clamp-1 text-[12px] text-gray-11">+ {headline}+ </span>+ )}+ <span className="flex items-center gap-1.5 text-[11.5px] text-gray-10">+ {products && <span className="truncate">{products}</span>}+ <RelativeTimestamp+ timestamp={report.created_at}+ className="shrink-0 text-[11.5px]"+ />+ </span>+ </div>+ <span className="flex shrink-0 items-center gap-2">+ <SuggestedReviewerAvatarStack report={report} />+ <SignalReportPriorityBadge priority={report.priority} />+ <span className="font-mono text-[12px] text-gray-11 tabular-nums">+ {report.signal_count} signal{report.signal_count === 1 ? "" : "s"}+ </span>+ {/* Acting on a row must not also open it. */}+ {/* biome-ignore lint/a11y/noStaticElementInteractions: propagation guard for the buttons inside, not interactive itself */}+ <span+ onClick={(event) => event.stopPropagation()}+ onKeyDown={(event) => event.stopPropagation()}+ className="flex items-center gap-1.5"+ >+ {pr && (+ <button+ type="button"+ onClick={() => {+ if (report.implementation_pr_url) {+ openExternalUrl(report.implementation_pr_url);+ }+ }}+ title={+ report.implementation_pr_merged+ ? "This report's earlier PR merged, but evidence kept arriving"+ : "Open the pull request on GitHub"+ }+ className="flex items-center gap-1 rounded border border-(--gray-6) px-1.5 py-0.5 font-mono text-[11px] text-gray-11 hover:bg-(--gray-3) hover:text-gray-12"+ >+ <GitPullRequestIcon size={11} />#{pr.number}+ {report.implementation_pr_merged ? " merged" : ""}+ </button>+ )}+ {report.implementation_pr_url &&+ !report.implementation_pr_merged && (+ <Button+ type="button"+ variant="primary"+ size="sm"+ onClick={() => navigateToInboxReportDetail(report.id)}+ >+ Review+ </Button>+ )}+ <span className="opacity-0 transition-opacity focus-within:opacity-100 group-hover:opacity-100">+ {archiveButton}+ </span>+ </span>+ </span>+ </div>+ {archiveDialog}+ </>+ );+}++// Archived and resolved reports come from their own server-side fetch, so the+// section fetches lazily on first expand and stays collapsed by default.+function ResolvedSection() {+ const [expanded, setExpanded] = useState(false);+ const {+ allReports,+ isLoading,+ hasNextPage,+ fetchNextPage,+ isFetchingNextPage,+ } = useInboxReportsInfinite(+ { status: INBOX_DISMISSED_STATUS_FILTER, ordering: "-updated_at" },+ { enabled: expanded, pageSize: 25 },+ );+ return (+ <section className="flex flex-col gap-1.5">+ <button+ type="button"+ onClick={() => setExpanded((v) => !v)}+ className="flex items-baseline gap-2 border-(--gray-5) border-b pb-1 text-left font-medium text-[11px] text-gray-10 uppercase tracking-wide"+ >+ Resolved+ <CaretDownIcon+ size={11}+ className={expanded ? "rotate-180 self-center" : "self-center"}+ />+ </button>+ {expanded &&+ (isLoading ? (+ <div className="flex justify-center py-3">+ <Spinner />+ </div>+ ) : allReports.length === 0 ? (+ <p className="px-1 py-2 text-[12.5px] text-gray-10">+ Nothing resolved yet.+ </p>+ ) : (+ <div className="flex flex-col gap-1">+ {allReports.map((report) => (+ <InboxReportRow key={report.id} report={report} />+ ))}+ {hasNextPage && (+ <Button+ type="button"+ variant="link-muted"+ size="sm"+ className="self-center text-gray-10"+ disabled={isFetchingNextPage}+ onClick={() => fetchNextPage()}+ >+ {isFetchingNextPage ? <Spinner /> : "Show more"}+ </Button>+ )}+ </div>+ ))}+ </section>+ );+}diff --git a/products/desktop/packages/ui/src/features/inbox/hooks/useInboxAllReports.ts b/products/desktop/packages/ui/src/features/inbox/hooks/useInboxAllReports.tsindex 0f55ab8f4b7f..370ebb80c4ef 100644--- a/products/desktop/packages/ui/src/features/inbox/hooks/useInboxAllReports.ts+++ b/products/desktop/packages/ui/src/features/inbox/hooks/useInboxAllReports.ts@@ -48,6 +48,11 @@ export function useInboxAllReports(options?: {pullRequestsOnly?: boolean;withReportsCount?: boolean;refetchIntervalMs?: number;+ /**+ * Overrides the pipeline status set (server-side, part of the query key).+ * Callers sharing one dataset must pass the same value.+ */+ statusFilter?: string;}) {const ignoreScope = options?.ignoreScope ?? false;const ignoreFilters = options?.ignoreFilters ?? false;@@ -92,7 +97,7 @@ export function useInboxAllReports(options?: {// matching its count query and the PostHog Cloud inbox.status: pullRequestsOnly? INBOX_PULL_REQUEST_STATUS_FILTER- : INBOX_PIPELINE_STATUS_FILTER,+ : (options?.statusFilter ?? INBOX_PIPELINE_STATUS_FILTER),has_implementation_pr: pullRequestsOnly ? true : undefined,ordering: buildSignalReportListOrdering(sortField, sortDirection),source_product:diff --git a/products/desktop/packages/ui/src/features/inbox/hooks/useInboxDecisionCount.ts b/products/desktop/packages/ui/src/features/inbox/hooks/useInboxDecisionCount.tsnew file mode 100644index 000000000000..080faa1c2292--- /dev/null+++ b/products/desktop/packages/ui/src/features/inbox/hooks/useInboxDecisionCount.ts@@ -0,0 +1,12 @@+import { useInboxSectionCounts } from "@posthog/ui/features/inbox/hooks/useInboxSectionCounts";++/**+ * The number the inbox badges show: the server-side count of ready reports+ * under the current reviewer scope (and any persisted source/priority+ * filters). The same count the inbox page's "Needs a decision" header shows,+ * from the same queries — so the badge and the page cannot disagree, and+ * neither depends on how many pages a client happened to load.+ */+export function useInboxDecisionCount(): number {+ return useInboxSectionCounts().decision;+}diff --git a/products/desktop/packages/ui/src/features/inbox/hooks/useInboxReportDismissAction.tsx b/products/desktop/packages/ui/src/features/inbox/hooks/useInboxReportDismissAction.tsxindex e943cc7d9cd8..51e91db1997c 100644--- a/products/desktop/packages/ui/src/features/inbox/hooks/useInboxReportDismissAction.tsx+++ b/products/desktop/packages/ui/src/features/inbox/hooks/useInboxReportDismissAction.tsx@@ -16,6 +16,8 @@ const EMPTY_REPORTS: SignalReport[] = [];export function useInboxReportDismissAction(report: SignalReport): {actionButton: ReactElement;dialog: ReactElement | null;+ /** Open the archive dialog directly — for menu items and keyboard paths. */+ openDialog: () => void;} {const [open, setOpen] = useState(false);// Stable identity for the closed case so `useInboxBulkActions`'s memo doesn't@@ -72,5 +74,6 @@ export function useInboxReportDismissAction(report: SignalReport): {/>) : null;- return { actionButton, dialog };+ const openDialog = useCallback(() => setOpen(true), []);+ return { actionButton, dialog, openDialog };}diff --git a/products/desktop/packages/ui/src/features/inbox/hooks/useInboxSectionCounts.ts b/products/desktop/packages/ui/src/features/inbox/hooks/useInboxSectionCounts.tsnew file mode 100644index 000000000000..0de5be2cecc0--- /dev/null+++ b/products/desktop/packages/ui/src/features/inbox/hooks/useInboxSectionCounts.ts@@ -0,0 +1,97 @@+import {+ buildPriorityFilterParam,+ buildSuggestedReviewerFilterParam,+} from "@posthog/core/inbox/reportFiltering";+import {+ INBOX_SCOPE_FOR_YOU,+ parseTeammateInboxScope,+} from "@posthog/core/inbox/reportMembership";+import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";+import { useCurrentUser } from "@posthog/ui/features/auth/useCurrentUser";+import { useInboxReports } from "@posthog/ui/features/inbox/hooks/useInboxReports";+import { useInboxReviewerScopeStore } from "@posthog/ui/features/inbox/stores/inboxReviewerScopeStore";+import { useInboxSignalsFilterStore } from "@posthog/ui/features/inbox/stores/inboxSignalsFilterStore";++/** The live statuses that aren't `ready`: what the Monitoring section holds. */+const MONITORING_STATUS_FILTER = "pending_input,failed,in_progress,candidate";++export interface InboxSectionCounts {+ /** Ready reports — the "Needs a decision" section's true total. */+ decision: number;+ /** The subset of ready reports carrying an implementation PR. */+ decisionPr: number;+ /** Everything else live: running, queued, waiting on input, failed. */+ monitoring: number;+ isLoading: boolean;+}++/**+ * Server-side counts for the inbox's sections and badges.+ *+ * At this dataset's real size (tens of thousands of live reports in a shared+ * project) any count derived from loaded pages is a count of a window, not of+ * reality — which is where every badge/section mismatch came from. So each+ * number here is a `limit: 1` count query on the dimensions the API can+ * actually filter server-side (status, PR presence, reviewer scope, source,+ * priority), and the sections are deliberately defined on those dimensions.+ *+ * Scope and the filter bar's source/priority choices are mirrored into every+ * query so the counts move with what the list shows. Search is not — it's a+ * client-side title match, so surfaces showing searched rows must count those+ * rows instead.+ */+export function useInboxSectionCounts(): InboxSectionCounts {+ const scope = useInboxReviewerScopeStore((s) => s.scope);+ const sourceProductFilter = useInboxSignalsFilterStore(+ (s) => s.sourceProductFilter,+ );+ const priorityFilter = useInboxSignalsFilterStore((s) => s.priorityFilter);+ const client = useOptionalAuthenticatedClient();+ const { data: currentUser } = useCurrentUser({ client });++ const isForYou = scope === INBOX_SCOPE_FOR_YOU;+ const teammateUuid = parseTeammateInboxScope(scope);+ const reviewerUuid =+ teammateUuid ?? (isForYou ? (currentUser?.uuid ?? null) : null);++ const shared = {+ source_product:+ sourceProductFilter.length > 0+ ? sourceProductFilter.join(",")+ : undefined,+ priority: buildPriorityFilterParam(priorityFilter),+ suggested_reviewers: reviewerUuid+ ? buildSuggestedReviewerFilterParam([reviewerUuid])+ : undefined,+ limit: 1,+ };+ const options = {+ // "For you" must carry the user's reviewer filter; hold until it resolves.+ enabled: !isForYou || reviewerUuid != null,+ refetchInterval: 60_000,+ refetchIntervalInBackground: false,+ };++ const decisionQuery = useInboxReports(+ { ...shared, status: "ready" },+ options,+ );+ const decisionPrQuery = useInboxReports(+ { ...shared, status: "ready", has_implementation_pr: true },+ options,+ );+ const monitoringQuery = useInboxReports(+ { ...shared, status: MONITORING_STATUS_FILTER },+ options,+ );++ return {+ decision: decisionQuery.data?.count ?? 0,+ decisionPr: decisionPrQuery.data?.count ?? 0,+ monitoring: monitoringQuery.data?.count ?? 0,+ isLoading:+ decisionQuery.isLoading ||+ monitoringQuery.isLoading ||+ (isForYou && reviewerUuid == null),+ };+}diff --git a/products/desktop/packages/ui/src/features/inbox/hooks/useReportTasks.test.ts b/products/desktop/packages/ui/src/features/inbox/hooks/useReportTasks.test.tsindex 0a541ac7ce17..34021fb6f0fe 100644--- a/products/desktop/packages/ui/src/features/inbox/hooks/useReportTasks.test.ts+++ b/products/desktop/packages/ui/src/features/inbox/hooks/useReportTasks.test.ts@@ -10,8 +10,19 @@ import {function makeTask(id: string,- run?: { status?: TaskRunStatus; prUrl?: string | null },+ run?: {+ status?: TaskRunStatus;+ prUrl?: string | null;+ prMerged?: boolean;+ prState?: string;+ },): Task {+ let output: Record<string, unknown> | null = null;+ if (run?.prUrl) {+ output = { pr_url: run.prUrl };+ if (run.prMerged) output.pr_merged = true;+ if (run.prState) output.pr_state = run.prState;+ }const latest_run: TaskRun | undefined = run? ({id: `${id}-run`,@@ -21,7 +32,7 @@ function makeTask(status: run.status ?? "in_progress",log_url: "",error_message: null,- output: run.prUrl ? { pr_url: run.prUrl } : null,+ output,state: {},created_at: "2026-06-24T10:00:00Z",updated_at: "2026-06-24T10:00:00Z",@@ -105,6 +116,46 @@ describe("findContinuableImplementationTask", () => {findContinuableImplementationTask([entry(failed), entry(running)]),).toBe(running);});++ it.each<[string, { prMerged?: boolean; prState?: string }]>([+ ["pr_state merged", { prState: "merged" }],+ ["legacy pr_merged flag", { prMerged: true }],+ ])(+ "treats a task whose PR already merged (%s) as not continuable",+ (_label, merge) => {+ const merged = makeTask("impl", {+ status: "completed",+ prUrl: "https://gh/pr/9",+ ...merge,+ });+ expect(findContinuableImplementationTask([entry(merged)])).toBeNull();+ },+ );++ it("prefers a still-running task over one whose PR already merged", () => {+ const merged = makeTask("merged", {+ status: "completed",+ prUrl: "https://gh/pr/9",+ prState: "merged",+ });+ const running = makeTask("running", { status: "in_progress" });+ expect(+ findContinuableImplementationTask([entry(merged), entry(running)]),+ ).toBe(running);+ });+});++describe("findLatestDiscussionTask", () => {+ it("returns the newest discussion and ignores other purposes", () => {+ const older = entry(makeTask("old-chat"), "discussion");+ older.startedAt = "2026-06-20T10:00:00Z";+ const newer = entry(makeTask("new-chat"), "discussion");+ newer.startedAt = "2026-06-24T10:00:00Z";+ const impl = entry(makeTask("impl", { prUrl: "https://gh/pr/1" }));+ expect(findLatestDiscussionTask([impl, older, newer])).toBe(newer.task);+ expect(findLatestDiscussionTask([impl])).toBeNull();+ expect(findLatestDiscussionTask(undefined)).toBeNull();+ });});describe("findLatestDiscussionTask", () => {diff --git a/products/desktop/packages/ui/src/features/inbox/hooks/useReportTasks.ts b/products/desktop/packages/ui/src/features/inbox/hooks/useReportTasks.tsindex b3adf9e0189d..96e695f6123d 100644--- a/products/desktop/packages/ui/src/features/inbox/hooks/useReportTasks.ts+++ b/products/desktop/packages/ui/src/features/inbox/hooks/useReportTasks.ts@@ -126,13 +126,26 @@ export function getTaskPrUrl(task: Task): string | null {return typeof prUrl === "string" && prUrl.length > 0 ? prUrl : null;}+/**+ * Whether a task's latest run reports its PR as merged. Newer runs carry+ * `pr_state: "merged"`; runs merged before `pr_state` existed only carry the+ * legacy `pr_merged` flag, so honor both (matches feedQuery's `prStateOf`).+ */+export function isTaskPrMerged(task: Task): boolean {+ const output = task.latest_run?.output;+ if (!output) return false;+ return output.pr_state === "merged" || output.pr_merged === true;+}+/*** Find an implementation task linked to the report whose work is still live, so* re-engaging the report should resume it rather than spin up a duplicate PR. A- * task is continuable when its latest run already produced a PR (the report's- * `implementation_pr_url` may be stale or not yet set, but the task knows) or is- * still running. A failed/cancelled run with no PR is *not* continuable — the- * user can legitimately start a fresh attempt there.+ * task is continuable when its latest run already produced a PR that is still+ * open (the report's `implementation_pr_url` may be stale or not yet set, but+ * the task knows) or is still running. A merged PR is history, not live work —+ * its branch is closed, so the report reads by its own state and a fresh+ * attempt starts a new PR. A failed/cancelled run with no PR is *not*+ * continuable either — the user can legitimately start a fresh attempt there.** Prefers a task with a PR over a merely-running one; `reportTasks` is already* implementation-first ordered, so the first match wins among equals.@@ -144,7 +157,9 @@ export function findContinuableImplementationTask(const implementation = reportTasks.filter((t) => t.purpose === "implementation",);- const withPr = implementation.find((t) => getTaskPrUrl(t.task));+ const withPr = implementation.find(+ (t) => getTaskPrUrl(t.task) && !isTaskPrMerged(t.task),+ );if (withPr) return withPr.task;const running = implementation.find((t) => {const status = t.task.latest_run?.status;diff --git a/products/desktop/packages/ui/src/features/sidebar/components/SidebarNavSection.test.tsx b/products/desktop/packages/ui/src/features/sidebar/components/SidebarNavSection.test.tsxindex 53e36b0bd38b..6ed71de50914 100644--- a/products/desktop/packages/ui/src/features/sidebar/components/SidebarNavSection.test.tsx+++ b/products/desktop/packages/ui/src/features/sidebar/components/SidebarNavSection.test.tsx@@ -43,9 +43,14 @@ vi.mock("@posthog/ui/router/useAppView", () => ({ useAppView }));// Channel reports defaults off here so the Inbox item renders; the flag-on// test flips it via `channelReportsFlag`.let channelReportsFlag = false;+let reportsInboxFlag = false;vi.mock("@posthog/ui/features/feature-flags/useFeatureFlag", () => ({useFeatureFlag: (flag: string) =>- flag === "posthog-desktop-channel-reports" ? channelReportsFlag : true,+ flag === "posthog-desktop-channel-reports"+ ? channelReportsFlag+ : flag === "posthog-desktop-reports-inbox"+ ? reportsInboxFlag+ : true,}));// These tests pin the legacy layout (flag off), where the "Enable channels"// toggle row is present.@@ -82,8 +87,11 @@ vi.mock("@posthog/ui/features/command-center/commandCenterStore", () => ({selector: (s: { cells: (string | null)[] }) => unknown,) => selector({ cells: [] }),}));+vi.mock("@posthog/ui/features/inbox/hooks/useInboxDecisionCount", () => ({+ useInboxDecisionCount: () => 0,+}));vi.mock("@posthog/ui/features/inbox/hooks/useInboxAllReports", () => ({- useInboxAllReports: () => ({ counts: { pulls: 0 } }),+ useInboxAllReports: () => ({ scopedReports: [], counts: { pulls: 0 } }),}));vi.mock("@posthog/ui/features/tasks/useTasks", () => ({useTasks: () => ({ data: [] }),@@ -201,6 +209,18 @@ describe("SidebarNavSection", () => {}});+ it("keeps the Inbox item when the reports inbox reclaims the slot", () => {+ channelReportsFlag = true;+ reportsInboxFlag = true;+ try {+ renderNav();+ expect(screen.getByRole("button", { name: /Inbox/ })).toBeInTheDocument();+ } finally {+ channelReportsFlag = false;+ reportsInboxFlag = false;+ }+ });+it("does not render the Channels mode toggle in navigation", () => {renderNav();diff --git a/products/desktop/packages/ui/src/features/sidebar/components/SidebarNavSection.tsx b/products/desktop/packages/ui/src/features/sidebar/components/SidebarNavSection.tsxindex 1a0d10e25942..6ad7ad2f7ce8 100644--- a/products/desktop/packages/ui/src/features/sidebar/components/SidebarNavSection.tsx+++ b/products/desktop/packages/ui/src/features/sidebar/components/SidebarNavSection.tsx@@ -8,7 +8,8 @@ import { useCommandCenterActiveCount } from "@posthog/ui/features/command-centerimport { useChannelReportsEnabled } from "@posthog/ui/features/feature-flags/useChannelReportsEnabled";import { useContextLayerFlag } from "@posthog/ui/features/feature-flags/useContextLayerFlag";import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";-import { useInboxAllReports } from "@posthog/ui/features/inbox/hooks/useInboxAllReports";+import { useReportsInboxEnabled } from "@posthog/ui/features/feature-flags/useReportsInboxEnabled";+import { useInboxDecisionCount } from "@posthog/ui/features/inbox/hooks/useInboxDecisionCount";import { openSettings } from "@posthog/ui/features/settings/hooks/useOpenSettings";import {CUSTOMIZABLE_NAV_ITEM_IDS,@@ -41,8 +42,6 @@ import { LoopsItem } from "./items/LoopsItem";import { NewTaskItem } from "./items/NewTaskItem";import { SearchItem } from "./items/SearchItem";-const SIDEBAR_INBOX_REFETCH_INTERVAL_MS = 60_000;-interface SidebarNavSectionProps {// The Command Center badge counts how many command-center cells point at a// live task. Deriving it needs the task list, which the Code pane's@@ -77,6 +76,8 @@ export function SidebarNavSection({// With channel reports on, spaces own reports (sidebar tab + feed) and the// inbox disappears as a destination.const channelReportsEnabled = useChannelReportsEnabled();+ const reportsInboxEnabled = useReportsInboxEnabled();+ const inboxDecisionCount = useInboxDecisionCount();const contextEnabled = useContextLayerFlag();const inSpaces = useRouterState({select: (state) => state.location.pathname.startsWith("/spaces"),@@ -94,18 +95,6 @@ export function SidebarNavSection({const isCommandCenterActive = view.type === "command-center";const isContextActive = view.type === "context";- // Open pull requests in the inbox — the main CTA, and the same count the inbox- // Pull requests tab shows, so the badge and the tab always agree.- // `ignoreFilters` keeps the badge stable against the inbox's filter chrome;- // scope still follows the user's For-you / project choice.- // The sidebar mounts on every route, so its badge polls slowly; opening the- // inbox adds its own 3s observers and React Query uses the shortest interval.- const { counts: inboxCounts } = useInboxAllReports({- ignoreFilters: true,- refetchIntervalMs: SIDEBAR_INBOX_REFETCH_INTERVAL_MS,- });- const inboxPullRequestCount = inboxCounts.pulls;-// Only subscribe to the task list when a parent hasn't already supplied the// count — keeps the standalone (Channels) render self-contained without// opening a redundant subscription when composed inside SidebarMenu.@@ -149,7 +138,9 @@ export function SidebarNavSection({),);const navItemAvailable: Record<CustomizableNavItemId, boolean> = {- inbox: !channelReportsEnabled,+ // The global reports inbox reclaims the slot from the channel-reports+ // takeover; without it, spaces own reports and the entry goes away.+ inbox: !channelReportsEnabled || reportsInboxEnabled,"command-center": true,contexts: contextEnabled,activity: bluebirdEnabled,@@ -170,7 +161,7 @@ export function SidebarNavSection({onClick={withNavTrack("inbox", navigateToInbox, depth, {href: "/inbox",})}- pullRequestCount={inboxPullRequestCount}+ decisionCount={inboxDecisionCount}/>),"command-center": (depth) => (diff --git a/products/desktop/packages/ui/src/features/sidebar/components/items/InboxItem.tsx b/products/desktop/packages/ui/src/features/sidebar/components/items/InboxItem.tsxindex e182e6908473..dcd3b791969e 100644--- a/products/desktop/packages/ui/src/features/sidebar/components/items/InboxItem.tsx+++ b/products/desktop/packages/ui/src/features/sidebar/components/items/InboxItem.tsx@@ -10,22 +10,22 @@ import { SidebarKbdHint } from "./SidebarKbdHint";interface InboxItemProps {isActive: boolean;onClick: MouseEventHandler<Element>;- pullRequestCount?: number;+ decisionCount?: number;depth?: number;}export function InboxItem({isActive,onClick,- pullRequestCount = 0,+ decisionCount = 0,depth = 0,}: InboxItemProps) {return (<Tooltipcontent={- pullRequestCount > 0- ? `${pullRequestCount} pull request${pullRequestCount === 1 ? "" : "s"} to review`- : "No pull requests to review"+ decisionCount > 0+ ? `${decisionCount} report${decisionCount === 1 ? " needs" : "s need"} a decision`+ : "No reports need a decision"}side="right">@@ -39,8 +39,8 @@ export function InboxItem({<>Inbox<SidebarCountBadge- count={pullRequestCount}- title={`${pullRequestCount} pull requests to review`}+ count={decisionCount}+ title={`${decisionCount} report${decisionCount === 1 ? " needs" : "s need"} a decision`}/></>}