Skip to content

: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.

feat(desktop): bring inbox experience up to parity with web (#80177)

Charles Vien81dfe51131c9
diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.ts
index 0edc0c33e57b..3d97f9777308 100644
--- a/products/desktop/packages/api-client/src/posthog-client.ts
+++ b/products/desktop/packages/api-client/src/posthog-client.ts
@@ -87,6 +87,7 @@ import type {
SignalReport,
SignalReportArtefact,
SignalReportArtefactsResponse,
+ SignalReportRefundReason,
SignalReportSignalsResponse,
SignalReportStatus,
SignalReportsQueryParams,
@@ -4310,6 +4311,41 @@ export class PostHogAPIClient {
return (await response.json()) as SignalReport;
}
+ /**
+ * Refund a report's billed PR. The server freezes the billing path, archives
+ * the report, and kicks off the billing credit when one is due; it also
+ * enforces eligibility, so callers only gate for display.
+ */
+ async refundSignalReport(
+ reportId: string,
+ input: { reason: SignalReportRefundReason; note?: string },
+ ): Promise<SignalReport> {
+ const teamId = await this.getTeamId();
+ const path = `/api/projects/${teamId}/signals/reports/${reportId}/refund/`;
+ const url = new URL(`${this.api.baseUrl}${path}`);
+
+ // The shared fetcher throws `Failed request: [<status>] <json-body>` for any non-2xx, so
+ // unwrap that into the endpoint's clean `error` message (e.g. the eligibility failures)
+ // rather than surfacing the raw string.
+ let response: Response;
+ try {
+ response = await this.api.fetcher.fetch({
+ method: "post",
+ url,
+ path,
+ overrides: {
+ body: JSON.stringify(input),
+ },
+ });
+ } catch (error) {
+ throw new Error(
+ extractRequestErrorMessage(error, "Failed to refund this report's PR"),
+ );
+ }
+
+ return (await response.json()) as SignalReport;
+ }
+
/**
* Edit a report's suggested reviewers. The server appends a new `suggested_reviewers` status
* artefact (latest-wins), canonicalizes each entry to a lowercase `github_login`, and carries
@@ -6851,6 +6887,34 @@ export class PostHogAPIClient {
return { results: data.results ?? [], columns: data.columns ?? [] };
}
+ /**
+ * Runs an arbitrary typed query node (TrendsQuery, HogQLQuery, ...) against
+ * the team's project and returns the raw response. `refresh: "blocking"`
+ * serves a fresh-enough cached result and computes synchronously otherwise —
+ * the same mode PostHog insights use. Backs inbox report charts, whose query
+ * nodes are scout-authored and arrive unparsed.
+ */
+ async runQuery(
+ query: Record<string, unknown>,
+ ): Promise<Record<string, unknown>> {
+ const teamId = await this.getTeamId();
+ const path = `/api/projects/${teamId}/query/`;
+ const url = new URL(`${this.api.baseUrl}${path}`);
+ const response = await this.api.fetcher.fetch({
+ method: "post",
+ url,
+ path,
+ overrides: {
+ body: JSON.stringify({ query, refresh: "blocking" }),
+ },
+ });
+ const data = (await response.json()) as Record<string, unknown>;
+ if (typeof data.error === "string" && data.error) {
+ throw new Error(data.error);
+ }
+ return data;
+ }
+
/**
* Agent observability rollup over the agents' `$ai_*` events — KPIs (spend,
* sessions, failure rate, p95), a 14-day daily trend + WoW deltas, and
diff --git a/products/desktop/packages/core/src/inbox/inboxQuery.ts b/products/desktop/packages/core/src/inbox/inboxQuery.ts
index 4eefc985f6fb..d43b68f619af 100644
--- a/products/desktop/packages/core/src/inbox/inboxQuery.ts
+++ b/products/desktop/packages/core/src/inbox/inboxQuery.ts
@@ -20,6 +20,8 @@ export const inboxReportKeys = {
[...inboxReportKeys.all, reportId, "detail"] as const,
artefacts: (reportId: string) =>
[...inboxReportKeys.all, reportId, "artefacts"] as const,
+ chartData: (reportId: string, chartId: string) =>
+ [...inboxReportKeys.all, reportId, "chart-data", chartId] as const,
signals: (reportId: string) =>
[...inboxReportKeys.all, reportId, "signals"] as const,
availableSuggestedReviewers: (authIdentity: string | null) =>
diff --git a/products/desktop/packages/core/src/inbox/reportCharts.test.ts b/products/desktop/packages/core/src/inbox/reportCharts.test.ts
new file mode 100644
index 000000000000..b6b4c4e0d498
--- /dev/null
+++ b/products/desktop/packages/core/src/inbox/reportCharts.test.ts
@@ -0,0 +1,292 @@
+import type { SignalReportChartSize } from "@posthog/shared/types";
+import { describe, expect, it } from "vitest";
+import {
+ planReportChart,
+ type ReportChartData,
+ type ReportChartPlan,
+ renderableReportChartIds,
+ reportChartHeightClass,
+ reportChartOpenTarget,
+ shapeReportChartData,
+} from "./reportCharts";
+
+const OPEN_OPTS = { cloudUrl: "https://us.posthog.com", projectId: 2 };
+
+const hogqlNode = (extra: Record<string, unknown> = {}) => ({
+ kind: "DataVisualizationNode",
+ source: { kind: "HogQLQuery", query: "SELECT 1" },
+ ...extra,
+});
+
+const trendsNode = (display?: string) => ({
+ kind: "InsightVizNode",
+ source: {
+ kind: "TrendsQuery",
+ series: [{ event: "$pageview" }],
+ ...(display ? { trendsFilter: { display } } : {}),
+ },
+});
+
+const runPlan = (query: unknown) => {
+ const plan = planReportChart(query);
+ if (plan.kind !== "run")
+ throw new Error(`expected run plan, got ${plan.kind}`);
+ return plan;
+};
+
+describe("reportCharts", () => {
+ it.each([
+ [null, "invalid"],
+ ["SELECT 1", "invalid"],
+ [{ noKind: true }, "invalid"],
+ [{ kind: "SavedInsightNode" }, "invalid"],
+ [{ kind: "SavedInsightNode", shortId: 42 }, "invalid"],
+ [{ kind: "SavedInsightNode", shortId: "abc123" }, "saved-insight"],
+ [{ kind: "InsightVizNode" }, "invalid"],
+ [{ kind: "InsightVizNode", source: { kind: "FunnelsQuery" } }, "open-only"],
+ [
+ { kind: "InsightVizNode", source: { kind: "RetentionQuery" } },
+ "open-only",
+ ],
+ [trendsNode(), "run"],
+ [
+ { kind: "DataVisualizationNode", source: { kind: "EventsQuery" } },
+ "open-only",
+ ],
+ [hogqlNode(), "run"],
+ [{ kind: "HogQuery", code: "return 1" }, "open-only"],
+ ] as [unknown, ReportChartPlan["kind"]][])(
+ "planReportChart(%j) -> %s",
+ (query, expected) => {
+ expect(planReportChart(query).kind).toBe(expected);
+ },
+ );
+
+ it.each([
+ [trendsNode(), "line"],
+ [trendsNode("ActionsBar"), "bar"],
+ [trendsNode("BoldNumber"), "number"],
+ [hogqlNode(), "auto"],
+ [hogqlNode({ display: "ActionsLineGraph" }), "line"],
+ [hogqlNode({ display: "ActionsBar" }), "bar"],
+ [hogqlNode({ display: "BoldNumber" }), "number"],
+ [hogqlNode({ display: "ActionsTable" }), "auto"],
+ ])("planReportChart(%j) picks render %s", (query, render) => {
+ expect(runPlan(query).render).toBe(render);
+ });
+
+ it("shapes a trends response into a time series", () => {
+ const data = shapeReportChartData(
+ {
+ results: [
+ {
+ label: "$pageview",
+ data: [1, 2, 3],
+ days: ["2026-08-01", "2026-08-02", "2026-08-03"],
+ },
+ ],
+ },
+ runPlan(trendsNode()),
+ );
+ expect(data).toEqual({
+ type: "series",
+ render: "line",
+ labels: ["2026-08-01", "2026-08-02", "2026-08-03"],
+ series: [{ key: "series-0", label: "$pageview", data: [1, 2, 3] }],
+ isTimeSeries: true,
+ interval: "day",
+ });
+ });
+
+ it("sums aggregated values for a BoldNumber trends chart", () => {
+ const data = shapeReportChartData(
+ { results: [{ aggregated_value: 41 }, { aggregated_value: 1 }] },
+ runPlan(trendsNode("BoldNumber")),
+ );
+ expect(data).toEqual({ type: "number", value: 42 });
+ });
+
+ it("normalizes midnight-stamped day buckets to plain dates", () => {
+ const data = shapeReportChartData(
+ {
+ columns: ["day", "errors"],
+ results: [
+ ["2026-07-26T00:00:00-07:00", 5],
+ ["2026-08-01T00:00:00-07:00", 8],
+ ],
+ },
+ runPlan(hogqlNode({ display: "ActionsBar" })),
+ );
+ expect(data).toMatchObject({
+ type: "series",
+ isTimeSeries: true,
+ interval: "day",
+ labels: ["2026-07-26", "2026-08-01"],
+ });
+ });
+
+ it("shapes a date + numeric HogQL grid into a time series", () => {
+ const data = shapeReportChartData(
+ {
+ columns: ["day", "errors"],
+ results: [
+ ["2026-08-01", 5],
+ ["2026-08-02", 8],
+ ],
+ },
+ runPlan(hogqlNode({ display: "ActionsLineGraph" })),
+ );
+ expect(data).toMatchObject({
+ type: "series",
+ render: "line",
+ isTimeSeries: true,
+ labels: ["2026-08-01", "2026-08-02"],
+ series: [{ label: "errors", data: [5, 8] }],
+ });
+ });
+
+ it("pivots a date + breakdown + value grid into one series per breakdown", () => {
+ const data = shapeReportChartData(
+ {
+ columns: ["day", "browser", "count"],
+ results: [
+ ["2026-08-01", "Chrome", 5],
+ ["2026-08-01", "Safari", 2],
+ ["2026-08-02", "Chrome", 7],
+ ],
+ },
+ runPlan(hogqlNode({ display: "ActionsBar" })),
+ );
+ expect(data).toMatchObject({
+ type: "series",
+ render: "bar",
+ labels: ["2026-08-01", "2026-08-02"],
+ series: [
+ { label: "Chrome", data: [5, 7] },
+ { label: "Safari", data: [2, 0] },
+ ],
+ });
+ });
+
+ it("keeps a categorical grid as a bar chart with string labels", () => {
+ const data = shapeReportChartData(
+ {
+ columns: ["scope", "count"],
+ results: [
+ ["granted", 12],
+ ["denied", 3],
+ ],
+ },
+ runPlan(hogqlNode({ display: "ActionsBar" })),
+ );
+ expect(data).toMatchObject({
+ type: "series",
+ render: "bar",
+ isTimeSeries: false,
+ labels: ["granted", "denied"],
+ });
+ });
+
+ it.each([
+ [
+ "single numeric cell becomes a number",
+ [[42]],
+ ["total"],
+ { type: "number", value: 42 },
+ ],
+ [
+ "non-numeric grid falls back to a table",
+ [["a", "b"]],
+ ["x", "y"],
+ { type: "table", columns: ["x", "y"], rows: [["a", "b"]] },
+ ],
+ ])("auto display: %s", (_name, results, columns, expected) => {
+ expect(
+ shapeReportChartData({ columns, results }, runPlan(hogqlNode())),
+ ).toMatchObject(expected);
+ });
+
+ it("returns empty for a response with no rows", () => {
+ expect(
+ shapeReportChartData({ columns: [], results: [] }, runPlan(hogqlNode())),
+ ).toEqual({ type: "empty" });
+ expect(
+ shapeReportChartData({ results: [] }, runPlan(trendsNode())),
+ ).toEqual({ type: "empty" });
+ });
+
+ const seriesData: ReportChartData = {
+ type: "series",
+ render: "line",
+ labels: ["2026-08-01"],
+ series: [{ key: "s0", label: "errors", data: [1] }],
+ isTimeSeries: true,
+ interval: "day",
+ };
+ // `size` arrives as stored JSON, so the guard has to survive values outside
+ // the declared union.
+ const unknownSize = "huge" as unknown as SignalReportChartSize;
+
+ it.each<[string, SignalReportChartSize | null, ReportChartData, string]>([
+ ["graphs get a fixed height", null, seriesData, "h-72"],
+ ["explicit size wins for graphs", "large", seriesData, "h-[28rem]"],
+ ["numbers default small", null, { type: "number", value: 1 }, "max-h-36"],
+ [
+ "tables get a scroll ceiling",
+ null,
+ { type: "table", columns: ["x"], rows: [[1]] },
+ "max-h-72",
+ ],
+ ["unknown size falls back", unknownSize, seriesData, "h-72"],
+ ])("%s", (_name, size, data, expected) => {
+ expect(reportChartHeightClass(size, data)).toBe(expected);
+ });
+
+ it("only offers jump targets for charts that will render", () => {
+ expect(
+ renderableReportChartIds([
+ { chart_id: "drawable", query: hogqlNode() },
+ { chart_id: "broken", query: { noKind: true } },
+ { chart_id: "fallback-card", query: { kind: "HogQuery" } },
+ ]),
+ ).toEqual(["drawable", "fallback-card"]);
+ expect(renderableReportChartIds(undefined)).toEqual([]);
+ });
+
+ it("links a saved insight to its insight page", () => {
+ expect(
+ reportChartOpenTarget(
+ { kind: "SavedInsightNode", shortId: "aBc12" },
+ OPEN_OPTS,
+ ),
+ ).toEqual({
+ url: "https://us.posthog.com/project/2/insights/aBc12",
+ label: "Open insight",
+ });
+ });
+
+ it("routes HogQL-backed nodes to the SQL editor with embed flags stripped", () => {
+ const target = reportChartOpenTarget(
+ hogqlNode({ embedded: true, showHeader: false }),
+ OPEN_OPTS,
+ );
+ expect(target?.label).toBe("Open in SQL editor");
+ expect(target?.url).toContain("/project/2/sql?open_query=");
+ expect(target?.url).not.toContain("embedded");
+ expect(target?.url).not.toContain("showHeader");
+ });
+
+ it("routes other nodes to a new insight", () => {
+ const target = reportChartOpenTarget(trendsNode(), OPEN_OPTS);
+ expect(target?.label).toBe("Open as new insight");
+ expect(target?.url).toContain("/project/2/insights/new?q=");
+ });
+
+ it.each([
+ ["no kind", { noKind: true }],
+ ["missing shortId", { kind: "SavedInsightNode" }],
+ ["URL past the request-line cap", hogqlNode({ padding: "x".repeat(9000) })],
+ ])("returns null when there is nowhere to link: %s", (_name, query) => {
+ expect(reportChartOpenTarget(query, OPEN_OPTS)).toBeNull();
+ });
+});
diff --git a/products/desktop/packages/core/src/inbox/reportCharts.ts b/products/desktop/packages/core/src/inbox/reportCharts.ts
new file mode 100644
index 000000000000..b50e8dc4e93f
--- /dev/null
+++ b/products/desktop/packages/core/src/inbox/reportCharts.ts
@@ -0,0 +1,409 @@
+import type { SignalReportChartSize } from "@posthog/shared/types";
+
+type QueryNode = Record<string, unknown>;
+
+export type ReportChartRender = "line" | "bar" | "number" | "auto";
+
+/**
+ * What to do with a chart's stored query. The backend only guarantees the
+ * top-level `kind`, so anything else in the node is treated as untrusted JSON:
+ * `run` means the source query can be executed via `/query/` and drawn with
+ * quill-charts, `saved-insight` and `open-only` degrade to a card that links
+ * out to PostHog, and `invalid` drops the chart body entirely.
+ */
+export type ReportChartPlan =
+ | { kind: "run"; source: QueryNode; render: ReportChartRender }
+ | { kind: "saved-insight"; shortId: string }
+ | { kind: "open-only" }
+ | { kind: "invalid" };
+
+function isRecord(value: unknown): value is QueryNode {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+function renderFromDisplay(display: unknown): ReportChartRender {
+ if (display === "BoldNumber") return "number";
+ if (display === "ActionsBar" || display === "ActionsBarValue") return "bar";
+ if (display === "ActionsLineGraph" || display === "ActionsAreaGraph") {
+ return "line";
+ }
+ return "auto";
+}
+
+export function planReportChart(query: unknown): ReportChartPlan {
+ if (!isRecord(query) || typeof query.kind !== "string") {
+ return { kind: "invalid" };
+ }
+ if (query.kind === "SavedInsightNode") {
+ return typeof query.shortId === "string" && query.shortId
+ ? { kind: "saved-insight", shortId: query.shortId }
+ : { kind: "invalid" };
+ }
+ const source = isRecord(query.source) ? query.source : null;
+ if (query.kind === "InsightVizNode") {
+ if (!source) return { kind: "invalid" };
+ if (source.kind !== "TrendsQuery" && source.kind !== "StickinessQuery") {
+ return { kind: "open-only" };
+ }
+ const filter =
+ source.kind === "TrendsQuery"
+ ? source.trendsFilter
+ : source.stickinessFilter;
+ const display = isRecord(filter) ? filter.display : undefined;
+ const render = renderFromDisplay(display);
+ return {
+ kind: "run",
+ source,
+ render: render === "auto" ? "line" : render,
+ };
+ }
+ if (query.kind === "DataVisualizationNode") {
+ if (!source || source.kind !== "HogQLQuery") {
+ return { kind: "open-only" };
+ }
+ return { kind: "run", source, render: renderFromDisplay(query.display) };
+ }
+ return { kind: "open-only" };
+}
+
+/**
+ * Ids of the charts that will actually mount a card (`invalid` plans render
+ * nothing), so summary `chart:` links only become in-page jumps when a target
+ * exists.
+ */
+export function renderableReportChartIds(
+ charts: readonly { chart_id: string; query: unknown }[] | undefined,
+): string[] {
+ return (charts ?? [])
+ .filter((chart) => planReportChart(chart.query).kind !== "invalid")
+ .map((chart) => chart.chart_id);
+}
+
+export interface ReportChartSeries {
+ key: string;
+ label: string;
+ data: number[];
+}
+
+export type ReportChartData =
+ | {
+ type: "series";
+ render: "line" | "bar";
+ labels: string[];
+ series: ReportChartSeries[];
+ isTimeSeries: boolean;
+ interval: "hour" | "day";
+ }
+ | { type: "number"; value: number }
+ | { type: "table"; columns: string[]; rows: unknown[][] }
+ | { type: "empty" };
+
+const MAX_SERIES = 15;
+const MAX_TABLE_ROWS = 100;
+
+const DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/;
+const DATE_TIME = /^\d{4}-\d{2}-\d{2}[T ]\d{2}/;
+
+function isDateLike(value: unknown): value is string {
+ return (
+ typeof value === "string" &&
+ (DATE_ONLY.test(value) || DATE_TIME.test(value))
+ );
+}
+
+function asFiniteNumber(value: unknown): number | null {
+ if (typeof value === "number" && Number.isFinite(value)) return value;
+ if (typeof value === "string" && value.trim() !== "") {
+ const parsed = Number(value);
+ return Number.isFinite(parsed) ? parsed : null;
+ }
+ return null;
+}
+
+function intervalFor(labels: string[]): "hour" | "day" {
+ return labels.some((label) => DATE_TIME.test(label)) ? "hour" : "day";
+}
+
+const MIDNIGHT_STAMP =
+ /^(\d{4}-\d{2}-\d{2})[T ]00:00:00(?:\.0+)?(?:Z|[+-]\d{2}:?\d{2})?$/;
+
+/**
+ * Day-bucketed results arrive as midnight timestamps carrying the project's
+ * UTC offset (`2026-07-26T00:00:00-07:00`). Formatting those in any fixed
+ * timezone can shift the calendar day, so when every label is a midnight
+ * stamp the time component is dropped and the backend's bucket date is the
+ * label.
+ */
+function normalizeDayLabels(labels: string[]): string[] {
+ if (labels.length === 0) return labels;
+ const matches = labels.map((label) => MIDNIGHT_STAMP.exec(label));
+ if (matches.some((match) => match === null)) return labels;
+ return matches.map((match) => (match as RegExpExecArray)[1]);
+}
+
+function shapeTrendsResponse(
+ response: QueryNode,
+ render: ReportChartRender,
+): ReportChartData {
+ const results = Array.isArray(response.results) ? response.results : [];
+ const seriesResults = results.filter(isRecord);
+ if (seriesResults.length === 0) return { type: "empty" };
+
+ if (render === "number") {
+ const total = seriesResults.reduce((sum, result) => {
+ const aggregated = asFiniteNumber(result.aggregated_value);
+ if (aggregated !== null) return sum + aggregated;
+ const data = Array.isArray(result.data) ? result.data : [];
+ return (
+ sum + data.reduce<number>((s, v) => s + (asFiniteNumber(v) ?? 0), 0)
+ );
+ }, 0);
+ return { type: "number", value: total };
+ }
+
+ const first = seriesResults[0];
+ const labels = (
+ Array.isArray(first.days) ? first.days : (first.labels ?? [])
+ ) as unknown[];
+ const stringLabels = normalizeDayLabels(labels.map(String));
+ if (stringLabels.length === 0) return { type: "empty" };
+
+ const series = seriesResults.slice(0, MAX_SERIES).map((result, index) => {
+ const data = (Array.isArray(result.data) ? result.data : []).map(
+ (v) => asFiniteNumber(v) ?? 0,
+ );
+ return {
+ key: `series-${index}`,
+ label:
+ typeof result.label === "string" && result.label
+ ? result.label
+ : `Series ${index + 1}`,
+ data,
+ };
+ });
+ return {
+ type: "series",
+ render: render === "bar" ? "bar" : "line",
+ labels: stringLabels,
+ series,
+ isTimeSeries: stringLabels.every(isDateLike),
+ interval: intervalFor(stringLabels),
+ };
+}
+
+function pivotBreakdownGrid(
+ rows: unknown[][],
+ columns: string[],
+): { labels: string[]; series: ReportChartSeries[] } | null {
+ const rawLabels = [...new Set(rows.map((row) => String(row[0])))];
+ const labels = normalizeDayLabels(rawLabels);
+ const breakdowns = [...new Set(rows.map((row) => String(row[1])))];
+ if (breakdowns.length > MAX_SERIES) return null;
+ // Rows are looked up by their raw first-column value; only the displayed
+ // labels are normalized.
+ const labelIndex = new Map(rawLabels.map((label, i) => [label, i]));
+ const series = breakdowns.map((name, index) => ({
+ key: `breakdown-${index}`,
+ label: name || columns[1] || `Series ${index + 1}`,
+ data: labels.map(() => 0),
+ }));
+ const seriesByName = new Map(breakdowns.map((name, i) => [name, series[i]]));
+ for (const row of rows) {
+ const target = seriesByName.get(String(row[1]));
+ const position = labelIndex.get(String(row[0]));
+ if (target && position !== undefined) {
+ target.data[position] = asFiniteNumber(row[2]) ?? 0;
+ }
+ }
+ return { labels, series };
+}
+
+function shapeHogQLResponse(
+ response: QueryNode,
+ render: ReportChartRender,
+): ReportChartData {
+ const rows = (Array.isArray(response.results) ? response.results : []).filter(
+ (row): row is unknown[] => Array.isArray(row),
+ );
+ const columns = (Array.isArray(response.columns) ? response.columns : []).map(
+ String,
+ );
+ if (rows.length === 0) return { type: "empty" };
+
+ const singleValue =
+ rows.length === 1 && rows[0].length === 1
+ ? asFiniteNumber(rows[0][0])
+ : null;
+ if (render === "number" || (render === "auto" && singleValue !== null)) {
+ const value =
+ singleValue ??
+ rows
+ .flat()
+ .map(asFiniteNumber)
+ .find((v) => v !== null);
+ return value !== null && value !== undefined
+ ? { type: "number", value }
+ : asTable(rows, columns);
+ }
+
+ if (render === "line" || render === "bar") {
+ const firstColumnDates = rows.every((row) => isDateLike(row[0]));
+ const width = rows[0].length;
+ const numericTail = (row: unknown[]): boolean =>
+ row.slice(1).every((cell) => asFiniteNumber(cell) !== null);
+
+ if (width === 3 && firstColumnDates && !numericTail(rows[0])) {
+ const pivoted = pivotBreakdownGrid(rows, columns);
+ if (pivoted && rows.every((row) => asFiniteNumber(row[2]) !== null)) {
+ return {
+ type: "series",
+ render,
+ labels: pivoted.labels,
+ series: pivoted.series,
+ isTimeSeries: true,
+ interval: intervalFor(pivoted.labels),
+ };
+ }
+ }
+ if (width >= 2 && rows.every(numericTail)) {
+ const labels = normalizeDayLabels(rows.map((row) => String(row[0])));
+ const series = columns.slice(1, 1 + MAX_SERIES).map((column, index) => ({
+ key: `column-${index}`,
+ label: column || `Series ${index + 1}`,
+ data: rows.map((row) => asFiniteNumber(row[index + 1]) ?? 0),
+ }));
+ return {
+ type: "series",
+ render,
+ labels,
+ series,
+ isTimeSeries: firstColumnDates,
+ interval: intervalFor(labels),
+ };
+ }
+ }
+
+ return asTable(rows, columns);
+}
+
+function asTable(rows: unknown[][], columns: string[]): ReportChartData {
+ return { type: "table", columns, rows: rows.slice(0, MAX_TABLE_ROWS) };
+}
+
+/**
+ * Shape a raw `/query/` response into a drawable model. The response shape
+ * depends on the source kind: trends return `results` as series objects,
+ * HogQL returns a `columns` + `results` grid.
+ */
+export function shapeReportChartData(
+ response: QueryNode,
+ plan: Extract<ReportChartPlan, { kind: "run" }>,
+): ReportChartData {
+ if (
+ plan.source.kind === "TrendsQuery" ||
+ plan.source.kind === "StickinessQuery"
+ ) {
+ return shapeTrendsResponse(response, plan.render);
+ }
+ return shapeHogQLResponse(response, plan.render);
+}
+
+const SIZE_HEIGHTS: Record<SignalReportChartSize, string> = {
+ small: "h-36",
+ medium: "h-72",
+ large: "h-[28rem]",
+};
+const SIZE_MAX_HEIGHTS: Record<SignalReportChartSize, string> = {
+ small: "max-h-36",
+ medium: "max-h-72",
+ large: "max-h-[28rem]",
+};
+
+/**
+ * A graph fills whatever box it is given, so it takes a fixed height; a table
+ * or number sizes to its content and only needs a ceiling to scroll within.
+ * Follows the web inbox sizing: `size` on the chart wins, numbers default
+ * small, everything else medium.
+ */
+export function reportChartHeightClass(
+ size: SignalReportChartSize | null | undefined,
+ data: ReportChartData | null,
+): string {
+ const valid = size && size in SIZE_HEIGHTS ? size : null;
+ if (data?.type === "series") {
+ return SIZE_HEIGHTS[valid ?? "medium"];
+ }
+ if (data?.type === "number") {
+ return SIZE_MAX_HEIGHTS[valid ?? "small"];
+ }
+ return SIZE_MAX_HEIGHTS[valid ?? "medium"];
+}
+
+export interface ReportChartOpenTarget {
+ url: string;
+ label: string;
+}
+
+// nginx refuses request lines past 8 KiB, and a chart query can be up to 20k
+// chars of JSON before encoding, so an over-long URL is dropped rather than
+// offered as a link that 414s.
+const MAX_OPEN_URL_LENGTH = 8000;
+
+const EMBED_PRESENTATION_KEYS = [
+ "full",
+ "embedded",
+ "showFilters",
+ "showHeader",
+ "showTable",
+ "showCorrelationTable",
+ "showResults",
+] as const;
+
+function withoutEmbedFlags(query: QueryNode): QueryNode {
+ const node = { ...query };
+ for (const key of EMBED_PRESENTATION_KEYS) {
+ delete node[key];
+ }
+ return node;
+}
+
+/**
+ * Where a chart's "open in PostHog" control points. Returns null when there is
+ * nowhere safe to send the reader (missing saved-insight id, or a query too
+ * large to fit in a URL), which is the caller's cue to drop the control.
+ */
+export function reportChartOpenTarget(
+ query: unknown,
+ options: { cloudUrl: string; projectId: number | string },
+): ReportChartOpenTarget | null {
+ if (!isRecord(query) || typeof query.kind !== "string") return null;
+ const projectBase = `${options.cloudUrl}/project/${options.projectId}`;
+
+ if (query.kind === "SavedInsightNode") {
+ if (typeof query.shortId !== "string" || !query.shortId) return null;
+ return {
+ url: `${projectBase}/insights/${encodeURIComponent(query.shortId)}`,
+ label: "Open insight",
+ };
+ }
+
+ const node = withoutEmbedFlags(query);
+ const source = isRecord(node.source) ? node.source : null;
+ const isHogQLBacked =
+ (node.kind === "DataVisualizationNode" || node.kind === "DataTableNode") &&
+ source?.kind === "HogQLQuery";
+
+ let url: string;
+ let label: string;
+ if (node.kind === "HogQLQuery" && typeof node.query === "string") {
+ url = `${projectBase}/sql?open_query=${encodeURIComponent(node.query)}`;
+ label = "Open in SQL editor";
+ } else if (isHogQLBacked) {
+ url = `${projectBase}/sql?open_query=${encodeURIComponent(JSON.stringify(node))}`;
+ label = "Open in SQL editor";
+ } else {
+ url = `${projectBase}/insights/new?q=${encodeURIComponent(JSON.stringify(node))}`;
+ label = "Open as new insight";
+ }
+ return url.length > MAX_OPEN_URL_LENGTH ? null : { url, label };
+}
diff --git a/products/desktop/packages/shared/src/domain-types.ts b/products/desktop/packages/shared/src/domain-types.ts
index 99406cb3f849..be81fcd70ad8 100644
--- a/products/desktop/packages/shared/src/domain-types.ts
+++ b/products/desktop/packages/shared/src/domain-types.ts
@@ -533,6 +533,21 @@ export type CommaSeparatedSignalReportStatuses =
| `${SignalReportStatus},${SignalReportStatus},${SignalReportStatus},${SignalReportStatus}`
| `${SignalReportStatus},${SignalReportStatus},${SignalReportStatus},${SignalReportStatus},${SignalReportStatus}`;
+export type SignalReportChartSize = "small" | "medium" | "large";
+
+/**
+ * One chart attached to a report (`SignalReport.charts` on the backend serializer).
+ * `query` is stored unparsed; the backend only guarantees `kind` is one of
+ * InsightVizNode, DataVisualizationNode, or SavedInsightNode.
+ */
+export interface SignalReportChart {
+ chart_id: string;
+ title: string;
+ query: unknown;
+ caption?: string | null;
+ size?: SignalReportChartSize | null;
+}
+
export interface SignalReport {
id: string;
title: string | null;
@@ -560,6 +575,27 @@ export interface SignalReport {
source_products?: string[];
/** PR URL from the latest implementation task run, if available. */
implementation_pr_url?: string | null;
+ /** 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). */
+ refund?: SignalReportRefund | null;
+ /** Marks reports that were never billable ("Free"), so there is nothing to refund. */
+ billing_exempt_reason?: string | null;
+ /** Backend-owned refund eligibility: why a refund would be rejected right now, null when it would be accepted. */
+ refund_ineligibility_reason?: string | null;
+}
+
+export type SignalReportRefundReason =
+ | "pr_incorrect"
+ | "pr_not_useful"
+ | "duplicate"
+ | "other";
+
+export interface SignalReportRefund {
+ id: string;
+ reason: SignalReportRefundReason;
+ note?: string | null;
+ created_at?: string;
}
export interface SignalReportArtefactContent {
diff --git a/products/desktop/packages/shared/src/flags.ts b/products/desktop/packages/shared/src/flags.ts
index 0cb88be68621..c644bd5bd140 100644
--- a/products/desktop/packages/shared/src/flags.ts
+++ b/products/desktop/packages/shared/src/flags.ts
@@ -51,3 +51,6 @@ export const STAGED_UPDATES_FLAG = "posthog-desktop-staged-updates";
export const ANNOUNCEMENTS_FLAG = "posthog-desktop-announcements";
/** Gates anchored comments across task, artifact, and Activity surfaces. */
export const COMMENTS_FLAG = "posthog-code-comments";
+
+/** Gates the PR-refund action in the inbox (matches the web SIGNALS_PR_REFUNDS flag). */
+export const SIGNALS_PR_REFUNDS_FLAG = "signals-pr-refunds";
diff --git a/products/desktop/packages/ui/src/features/editor/components/MarkdownRenderer.tsx b/products/desktop/packages/ui/src/features/editor/components/MarkdownRenderer.tsx
index ebd830c2ed01..5722b6fdf2eb 100644
--- a/products/desktop/packages/ui/src/features/editor/components/MarkdownRenderer.tsx
+++ b/products/desktop/packages/ui/src/features/editor/components/MarkdownRenderer.tsx
@@ -29,7 +29,11 @@ function preprocessMarkdown(content: string): string {
return content.replace(/\n([^\n].*)\n(---+|___+|\*\*\*+)\n/g, "\n$1\n\n$2\n");
}
-function markdownUrlTransform(value: string): string {
+function markdownUrlTransform(value: string, key: string): string {
+ // Report summaries reference their charts as `[label](chart:<id>)` links.
+ // The scheme survives only on `href` so `![x](chart:y)` can't become an
+ // unsanitized image; consumers decide what a chart href renders as.
+ if (key === "href" && value.startsWith("chart:")) return value;
if (isPostHogCodeDeeplink(value)) return value;
return defaultUrlTransform(value);
}
diff --git a/products/desktop/packages/ui/src/features/inbox/AGENTS.md b/products/desktop/packages/ui/src/features/inbox/AGENTS.md
index 5c819bb064c3..2382ba62924d 100644
--- a/products/desktop/packages/ui/src/features/inbox/AGENTS.md
+++ b/products/desktop/packages/ui/src/features/inbox/AGENTS.md
@@ -106,7 +106,11 @@ The Inbox reads from PostHog Cloud's Self-driving backend, currently implemented
- `GET /api/projects/{teamId}/signals/reports/{id}/artefacts/`: structured report artefacts.
- `GET /api/projects/{teamId}/signals/reports/{id}/tasks/`: tasks linked to a report.
-The shared renderer type for the report is `SignalReport` in `apps/code/src/shared/types.ts`. If the backend serializer changes, update that type and the normalizers in `posthogClient.ts` together.
+The shared renderer type for the report is `SignalReport` in `packages/shared/src/domain-types.ts`. If the backend serializer changes, update that type and the client methods in `packages/api-client/src/posthog-client.ts` together.
+
+Report charts: `SignalReport.charts` carries scout-authored chart definitions (`chart_id`, `title`, `query`, `caption?`, `size?`). The desktop app renders them natively in the detail views: `packages/core/src/inbox/reportCharts.ts` classifies the stored query (runnable HogQL/trends vs saved-insight vs link-out fallback), `PostHogAPIClient.runQuery` executes runnable sources against `/api/projects/{teamId}/query/`, and `components/detail/ReportChartCard.tsx` draws the result with `@posthog/quill-charts`. Query kinds the app can't draw degrade to a card that links out to PostHog. Summary prose references charts as `[label](chart:<chart_id>)` links; `SignalReportSummaryMarkdown` turns those into in-page jumps to the chart card (plain text on list rows).
+
+PR refunds: `POST /api/projects/{teamId}/signals/reports/{id}/refund/` refunds a billed PR and archives the report (`PostHogAPIClient.refundSignalReport`). The action is gated behind the `signals-pr-refunds` flag (`SIGNALS_PR_REFUNDS_FLAG`) and `utils/refundEligibility.ts`'s `computeRefundEligibility`, which reads `implementation_pr_url`, `refund` (one `SignalReportRefund` per report, ever), `billing_exempt_reason`, and the backend-owned `refund_ineligibility_reason`. The server enforces the same rules, so the gate is display-only; `ReportRefundAction` shows nothing when the report is ineligible.
Card headlines are derived client-side from `summary` by `utils/reportPresentation.ts`; there is no backend headline field.
@@ -137,7 +141,7 @@ Components come from `@posthog/quill`; layout is `div`s with Tailwind. Radix is
- Do not add any `@radix-ui/*` import. Use `@posthog/quill` plus `div` + Tailwind.
- Do not reuse the deleted legacy `ReportListRow`, `ReportDetailPane`, or old list/detail stores.
- Do not put page-level Inbox title or navigation into the global app header; `InboxView` owns the Inbox page chrome.
-- Do not add a configure shortcut back into the Inbox header; Responders configuration is a sidebar destination.
+- Responder configuration stays at `/code/agents`. The Inbox header carries a "Configure agents" link to it, but do not embed configuration UI in the Inbox itself.
- Scout (`signals_scout`) is a real Cloud source product. Keep it covered wherever source products surface: `INBOX_SOURCE_OPTIONS`, `SOURCE_PRODUCT_META`, and the scout-name display in `SignalCard`.
- Scout management UI (fleet configuration, run history) lives in `features/scouts/` and is backed by the PostHog Cloud scout endpoints (`/api/projects/{teamId}/signals/scout/`). Do not add scout controls that have no backing endpoint there.
- Do not put preview shims or mock report data in `apps/code/index.html`; the app shell should stay minimal.
diff --git a/products/desktop/packages/ui/src/features/inbox/components/AgentRunCard.tsx b/products/desktop/packages/ui/src/features/inbox/components/AgentRunCard.tsx
index 2e5a57063eb7..f56d431ebe06 100644
--- a/products/desktop/packages/ui/src/features/inbox/components/AgentRunCard.tsx
+++ b/products/desktop/packages/ui/src/features/inbox/components/AgentRunCard.tsx
@@ -14,7 +14,6 @@ import {
import { InboxMetaSourceStack } from "@posthog/ui/features/inbox/components/InboxMetaSourceStack";
import { InboxBadge } from "@posthog/ui/features/inbox/components/utils/InboxBadge";
import { hasKnownSourceProduct } from "@posthog/ui/features/inbox/components/utils/source-product-icons";
-import { Flex, Text } from "@radix-ui/themes";
import { useNavigate } from "@tanstack/react-router";
export type RunVariant = "queued" | "live" | "completed" | "failed";
@@ -82,17 +81,15 @@ function pickTimestamp(report: SignalReport, variant: RunVariant): string {
function RunStatusOrb({ meta }: { meta: VariantMeta }) {
return (
- <Flex
- align="center"
- justify="center"
- className={`h-7 w-7 shrink-0 rounded-full ring-1 ring-inset ${meta.orbClass}`}
+ <div
+ className={`flex h-7 w-7 shrink-0 items-center justify-center rounded-full ring-1 ring-inset ${meta.orbClass}`}
>
<span
className={`block h-1.5 w-1.5 rounded-full ${meta.dotClass}`}
role="img"
aria-label={meta.ariaLabel}
/>
- </Flex>
+ </div>
);
}
@@ -118,18 +115,23 @@ export function AgentRunCard({ report }: AgentRunCardProps) {
params: { reportId: report.id },
})
}
- className="group flex w-full items-start gap-3 rounded-(--radius-2) border border-border bg-(--color-panel-solid) px-4 py-3.5 text-left transition duration-150 hover:border-(--gray-6) hover:bg-(--gray-2) hover:shadow-sm focus-visible:bg-(--gray-2) focus-visible:outline-none"
+ className="group relative flex w-full items-start gap-3 rounded-(--radius-2) border border-border bg-(--color-panel-solid) px-4 py-3.5 text-left transition duration-150 hover:border-(--gray-6) hover:bg-(--gray-2) hover:shadow-sm focus-visible:bg-(--gray-2) focus-visible:outline-none"
>
+ <div className="absolute top-3.5 right-4">
+ <InboxBadge variant={meta.badgeTone}>{meta.label}</InboxBadge>
+ </div>
+
<RunStatusOrb meta={meta} />
- <Flex direction="column" gap="1.5" className="min-w-0 flex-1">
- <Text className="wrap-break-word min-w-0 font-semibold text-[14px] text-gray-11 leading-snug tracking-tight">
+ <div className="flex min-w-0 flex-1 flex-col gap-1.5">
+ {/* Pad clear of the absolute status badge. */}
+ <span className="wrap-break-word min-w-0 pr-20 font-semibold text-[14px] text-gray-11 leading-snug tracking-tight">
{report.title ?? "Untitled run"}
- </Text>
+ </span>
{headline ? (
- <Text className="wrap-break-word line-clamp-2 text-[12.5px] text-gray-10 leading-snug">
+ <span className="wrap-break-word line-clamp-2 text-[12.5px] text-gray-10 leading-snug">
{headline}
- </Text>
+ </span>
) : null}
<InboxMetaRow className="mt-1.5">
{hasSource ? (
@@ -142,21 +144,12 @@ export function AgentRunCard({ report }: AgentRunCardProps) {
{RUN_VARIANT_TIMESTAMP_LABEL[variant]}{" "}
{formatRelativeTimeLong(timestampSource)}
</InboxMetaText>
+ <InboxMetaSeparator />
+ <InboxMetaText mono className="text-[11px]">
+ {runId}
+ </InboxMetaText>
</InboxMetaRow>
- </Flex>
-
- <Flex
- align="end"
- direction="column"
- justify="center"
- gap="1.5"
- className="self-stretch border-border border-l pl-3"
- >
- <InboxBadge variant={meta.badgeTone}>{meta.label}</InboxBadge>
- <InboxMetaText mono className="text-[11px]">
- {runId}
- </InboxMetaText>
- </Flex>
+ </div>
</button>
);
}
diff --git a/products/desktop/packages/ui/src/features/inbox/components/ConventionalCommitScopeTag.tsx b/products/desktop/packages/ui/src/features/inbox/components/ConventionalCommitScopeTag.tsx
index 8da94401ef7b..dae79e406b1b 100644
--- a/products/desktop/packages/ui/src/features/inbox/components/ConventionalCommitScopeTag.tsx
+++ b/products/desktop/packages/ui/src/features/inbox/components/ConventionalCommitScopeTag.tsx
@@ -21,13 +21,16 @@ export function ConventionalCommitScopeTag({
const IconComponent = meta.icon;
const label = formatConventionalCommitTag(type, scope);
+ // `align-middle` keeps the tag centered on the title's first line when it
+ // renders as an inline prefix inside the title text; `font-normal` stops it
+ // inheriting the title's weight.
return (
<InboxBadge
variant={compact ? "default" : meta.variant}
className={cn(
"shrink-0 gap-1 font-mono",
compact &&
- "h-5 gap-0.5 border border-(--gray-4) bg-(--gray-2) px-1.5 py-0 text-[11px] text-gray-11 leading-none",
+ "mr-1.5 h-5 gap-0.5 border border-(--gray-4) bg-(--gray-2) px-1.5 py-0 align-middle font-normal text-[11px] text-gray-11 leading-none",
)}
title={label}
>
diff --git a/products/desktop/packages/ui/src/features/inbox/components/DetailSection.tsx b/products/desktop/packages/ui/src/features/inbox/components/DetailSection.tsx
index c72d7878163e..7ddb79196552 100644
--- a/products/desktop/packages/ui/src/features/inbox/components/DetailSection.tsx
+++ b/products/desktop/packages/ui/src/features/inbox/components/DetailSection.tsx
@@ -1,38 +1,87 @@
-import type { IconProps } from "@phosphor-icons/react";
-import { Flex, Text } from "@radix-ui/themes";
-import type { ComponentType, ReactNode } from "react";
+import { CaretDownIcon, type IconProps } from "@phosphor-icons/react";
+import { cn } from "@posthog/quill";
+import { type ComponentType, type ReactNode, useState } from "react";
-interface DetailSectionProps {
+export interface DetailSectionProps {
Icon: ComponentType<IconProps>;
title: string;
rightSlot?: ReactNode;
+ /**
+ * Collapsible header, like the web detail's cards. The title area and the
+ * chevron toggle; `rightSlot` stays outside the toggle so interactive
+ * controls in it (filter checkboxes, counts with tooltips) keep working.
+ */
+ collapsible?: boolean;
+ defaultCollapsed?: boolean;
children: ReactNode;
}
+/**
+ * Bordered card with a titled header, the shared chrome for every detail-view
+ * section (summary, checks, evidence, activity), following the web inbox's
+ * card-per-section detail layout.
+ */
export function DetailSection({
Icon,
title,
rightSlot,
+ collapsible = false,
+ defaultCollapsed = false,
children,
}: DetailSectionProps) {
+ const [collapsed, setCollapsed] = useState(collapsible && defaultCollapsed);
+ const toggle = () => setCollapsed((current) => !current);
+ const open = !(collapsible && collapsed);
+
+ const titleCluster = (
+ <>
+ <Icon size={14} weight="bold" className="shrink-0 text-gray-11" />
+ <span className="truncate font-semibold text-[13px] text-gray-12 tracking-[-0.01em]">
+ {title}
+ </span>
+ </>
+ );
+
return (
- <Flex direction="column" gap="3">
- <Flex
- align="center"
- justify="between"
- gap="3"
- className="min-w-0 cursor-default select-none"
+ <section className="flex min-w-0 flex-col rounded-(--radius-2) border border-(--gray-4) bg-(--color-panel-solid)">
+ <header
+ className={cn(
+ "flex select-none items-center gap-3 px-3.5",
+ open && "border-(--gray-4) border-b",
+ collapsible ? "py-0" : "cursor-default py-2.5",
+ )}
>
- <Flex align="center" gap="2" className="min-w-0">
- <Icon size={15} weight="bold" className="shrink-0 text-gray-11" />
- <Text className="truncate font-semibold text-[14px] text-gray-12 tracking-[-0.01em]">
- {title}
- </Text>
- </Flex>
- <div className="h-px min-w-4 flex-1 bg-(--gray-5)" />
+ {collapsible ? (
+ <button
+ type="button"
+ onClick={toggle}
+ aria-expanded={open}
+ className="flex min-w-0 flex-1 items-center gap-2 py-2.5 text-left"
+ >
+ {titleCluster}
+ </button>
+ ) : (
+ <div className="flex min-w-0 flex-1 items-center gap-2">
+ {titleCluster}
+ </div>
+ )}
{rightSlot && <div className="shrink-0">{rightSlot}</div>}
- </Flex>
- <div>{children}</div>
- </Flex>
+ {collapsible && (
+ <button
+ type="button"
+ onClick={toggle}
+ aria-expanded={open}
+ aria-label={open ? `Collapse ${title}` : `Expand ${title}`}
+ className="shrink-0 rounded-(--radius-1) p-1 text-gray-10 hover:bg-(--gray-3) hover:text-gray-12"
+ >
+ <CaretDownIcon
+ size={13}
+ className={cn("transition-transform", !open && "-rotate-90")}
+ />
+ </button>
+ )}
+ </header>
+ {open && <div className="min-w-0 p-3.5">{children}</div>}
+ </section>
);
}
diff --git a/products/desktop/packages/ui/src/features/inbox/components/DismissedTab.tsx b/products/desktop/packages/ui/src/features/inbox/components/DismissedTab.tsx
index 668b779afb05..377ef9dee051 100644
--- a/products/desktop/packages/ui/src/features/inbox/components/DismissedTab.tsx
+++ b/products/desktop/packages/ui/src/features/inbox/components/DismissedTab.tsx
@@ -11,7 +11,6 @@ import { InboxLoadMore } from "@posthog/ui/features/inbox/components/InboxLoadMo
import { ReportCard } from "@posthog/ui/features/inbox/components/ReportCard";
import { useInboxDismissedReports } from "@posthog/ui/features/inbox/hooks/useInboxDismissedReports";
import { useInboxRestoreReport } from "@posthog/ui/features/inbox/hooks/useInboxRestoreReport";
-import { Flex } from "@radix-ui/themes";
/**
* Archive tab: terminal reports, newest first — ones the user archived
@@ -27,15 +26,15 @@ export function DismissedTab() {
if (isLoading && reports.length === 0) {
return (
- <Flex direction="column" gap="4" className="mx-auto max-w-4xl px-6 py-4">
+ <div className="@container mx-auto flex w-full max-w-4xl flex-col gap-4 px-6 py-4">
<CardSkeleton count={4} variant="cards" />
- </Flex>
+ </div>
);
}
if (reports.length === 0) {
return (
- <Flex direction="column" className="mx-auto max-w-4xl px-6 py-4">
+ <div className="mx-auto flex w-full max-w-4xl flex-col px-6 py-4">
<Empty className="mx-auto max-w-md py-16">
<EmptyHeader>
<EmptyMedia variant="icon">
@@ -49,12 +48,12 @@ export function DismissedTab() {
</EmptyDescription>
</EmptyHeader>
</Empty>
- </Flex>
+ </div>
);
}
return (
- <Flex direction="column" gap="3" className="mx-auto max-w-4xl px-6 py-4">
+ <div className="@container mx-auto flex w-full max-w-4xl flex-col gap-3 px-6 py-4">
{reports.map((report) => (
<ReportCard
key={report.id}
@@ -69,6 +68,6 @@ export function DismissedTab() {
isFetchingNextPage={isFetchingNextPage}
onLoadMore={() => void fetchNextPage({ cancelRefetch: false })}
/>
- </Flex>
+ </div>
);
}
diff --git a/products/desktop/packages/ui/src/features/inbox/components/InboxCardChrome.tsx b/products/desktop/packages/ui/src/features/inbox/components/InboxCardChrome.tsx
new file mode 100644
index 000000000000..281a91f95e9d
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/inbox/components/InboxCardChrome.tsx
@@ -0,0 +1,89 @@
+import { cn } from "@posthog/quill";
+import type { ReactNode } from "react";
+
+/**
+ * Shared layout chrome for inbox list cards, following the web inbox's
+ * unified ReportCard: one column at narrow container widths, a
+ * [body | actions rail] row from `@lg` up. Requires an `@container` ancestor,
+ * which the list shells own. The card root is `relative` so the timestamp and
+ * top-right badge slots can pin to its corners in the row layout.
+ */
+export function inboxCardClassName(options: {
+ dashed?: boolean;
+ isSelected?: boolean;
+ dimmed?: boolean;
+}): string {
+ return cn(
+ "group relative flex w-full flex-col gap-2.5 @lg:flex-row @lg:items-stretch @lg:gap-3",
+ "rounded-(--radius-2) border bg-(--color-panel-solid) px-4 py-3.5 transition duration-150 hover:bg-(--gray-2)",
+ options.dashed
+ ? "border-(--gray-6) border-dashed hover:border-(--gray-7)"
+ : "border-border hover:border-(--gray-6) hover:shadow-sm",
+ options.dimmed && "opacity-90",
+ options.isSelected &&
+ "border-(--accent-8) bg-(--accent-2) ring-(--accent-8) ring-2 ring-inset",
+ );
+}
+
+export const inboxCardBodyClassName =
+ "flex min-w-0 flex-1 items-start gap-3 text-left text-inherit no-underline focus-visible:outline-none";
+
+/**
+ * Actions rail. In the column layout it is a plain right-aligned row under
+ * the body; from `@lg` it stretches beside the body and gains the left
+ * divider, so the border never renders as a floating rule above stacked
+ * content.
+ */
+export function InboxCardActions({
+ children,
+ className,
+}: {
+ children: ReactNode;
+ className?: string;
+}) {
+ return (
+ <div
+ className={cn(
+ "flex shrink-0 items-center justify-end gap-2.5 @lg:self-stretch border-border @lg:border-l @lg:pl-3",
+ className,
+ )}
+ >
+ {children}
+ </div>
+ );
+}
+
+export function InboxCardTopRight({ children }: { children: ReactNode }) {
+ return <div className="absolute top-3.5 right-4 z-10">{children}</div>;
+}
+
+/**
+ * Last-updated stamp: in flow at the end of the body in the column layout,
+ * pinned to the card's bottom-right corner from `@lg`.
+ */
+export function InboxCardTimestamp({
+ timestamp,
+ label,
+}: {
+ timestamp: string | null | undefined;
+ label?: string;
+}) {
+ const date = timestamp ? new Date(timestamp) : null;
+ if (!date || Number.isNaN(date.getTime())) {
+ return null;
+ }
+ const formatted = date.toLocaleDateString(undefined, {
+ month: "short",
+ day: "numeric",
+ });
+ return (
+ <div className="@lg:absolute @lg:right-4 @lg:bottom-3 @lg:z-10 @lg:mt-0 mt-0.5">
+ <span
+ className="text-[12px] text-gray-10 tabular-nums"
+ title={label ?? "Last updated"}
+ >
+ {formatted}
+ </span>
+ </div>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/inbox/components/InboxCardTitle.tsx b/products/desktop/packages/ui/src/features/inbox/components/InboxCardTitle.tsx
index 909ca9415ac6..440316a1df3d 100644
--- a/products/desktop/packages/ui/src/features/inbox/components/InboxCardTitle.tsx
+++ b/products/desktop/packages/ui/src/features/inbox/components/InboxCardTitle.tsx
@@ -1,18 +1,23 @@
-import { Text } from "@radix-ui/themes";
import type { ReactNode } from "react";
interface InboxCardTitleProps {
+ /**
+ * Conventional-commit scope tag, rendered as an inline prefix to the title
+ * text (not a flex sibling), so it stays on the title's first line and the
+ * title wraps beneath it instead of centering vertically beside the tag.
+ */
+ tag?: ReactNode;
children: ReactNode;
}
-export function InboxCardTitle({ children }: InboxCardTitleProps) {
+export function InboxCardTitle({ tag, children }: InboxCardTitleProps) {
return (
- <Text
- as="span"
- className="min-w-0 flex-1 break-words font-semibold text-[14px] text-gray-11 leading-snug tracking-tight"
+ <span
+ className="min-w-0 break-words font-semibold text-[14px] text-gray-11 leading-snug tracking-tight"
style={{ fontFamily: "var(--heading-font-family, var(--font-sans))" }}
>
+ {tag}
{children}
- </Text>
+ </span>
);
}
diff --git a/products/desktop/packages/ui/src/features/inbox/components/InboxDetailFrame.tsx b/products/desktop/packages/ui/src/features/inbox/components/InboxDetailFrame.tsx
index e122dcd0ae8c..6fdb949e800c 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,9 @@
import type { IconProps } from "@phosphor-icons/react";
+import { renderableReportChartIds } from "@posthog/core/inbox/reportCharts";
+import { Tabs, TabsList, TabsTrigger } from "@posthog/quill";
import type { SignalReport } from "@posthog/shared/types";
import { DetailSection } from "@posthog/ui/features/inbox/components/DetailSection";
+import { ReportChartsSection } from "@posthog/ui/features/inbox/components/detail/ReportChartCard";
import { InboxDetailPageHeader } from "@posthog/ui/features/inbox/components/InboxDetailPageHeader";
import {
InboxMetaSeparator,
@@ -22,8 +25,7 @@ import type { InboxListRoute } from "@posthog/ui/features/inbox/hooks/useInboxBa
import { useInboxReportDismissAction } from "@posthog/ui/features/inbox/hooks/useInboxReportDismissAction";
import { useInboxReportSignals } from "@posthog/ui/features/inbox/hooks/useInboxReports";
import { RelativeTimestamp } from "@posthog/ui/primitives/RelativeTimestamp";
-import { Flex, Text } from "@radix-ui/themes";
-import type { ComponentType, ReactNode } from "react";
+import { type ComponentType, type ReactNode, useState } from "react";
interface InboxDetailFrameProps {
report: SignalReport;
@@ -50,14 +52,21 @@ interface InboxDetailFrameProps {
Icon: ComponentType<IconProps>;
title: string;
};
- /** Sections rendered in the main column under the summary (e.g. PR files changed). */
+ /** Sections rendered in the main column under the summary (e.g. PR comments). */
belowSummary?: ReactNode;
/** Optional "Evidence" section icon + title; null hides it. */
evidenceSection: {
Icon: ComponentType<IconProps>;
title: string;
} | null;
- /** Sections rendered alongside the summary (Tasks, Suggested reviewers, …). */
+ /** Right-column cards rendered above the Evidence card (checks, reviewers). */
+ aboveEvidence?: ReactNode;
+ /**
+ * Second tab beside Overview (the web detail's "Files changed"). Its content
+ * replaces the whole overview grid while selected.
+ */
+ secondaryTab?: { label: ReactNode; content: ReactNode };
+ /** Sections rendered alongside the summary (Tasks, Activity, …). */
children?: ReactNode;
}
@@ -81,9 +90,12 @@ export function InboxDetailFrame({
summarySection,
belowSummary,
evidenceSection,
+ aboveEvidence,
+ secondaryTab,
showDismiss = true,
children,
}: InboxDetailFrameProps) {
+ const [activeTab, setActiveTab] = useState("overview");
const { data: signalsResp } = useInboxReportSignals(report.id);
const signals = signalsResp?.signals ?? [];
const signalsLoaded = signalsResp !== undefined;
@@ -101,7 +113,7 @@ export function InboxDetailFrame({
evidenceSection != null && EvidenceIcon != null && evidenceCount > 0;
return (
- <Flex direction="column" className="min-h-full">
+ <div className="flex min-h-full flex-col">
<InboxDetailPageHeader
backTo={backTo}
backLabel={backLabel}
@@ -159,13 +171,30 @@ export function InboxDetailFrame({
</>
}
actions={
- <Flex align="center" className="gap-2.5">
- {showDismiss && dismissButton}
+ <div className="flex items-center gap-2.5">
{primaryAction}
- </Flex>
+ {showDismiss && dismissButton}
+ </div>
}
/>
+ {secondaryTab && (
+ <div className="border-(--gray-5) border-b px-6">
+ <Tabs value={activeTab} onValueChange={setActiveTab}>
+ <TabsList variant="line" className="h-auto gap-0.5">
+ <TabsTrigger value="overview" className="gap-1.5 px-2.5 py-2">
+ <span className="font-medium text-[13px]">Overview</span>
+ </TabsTrigger>
+ <TabsTrigger value="secondary" className="gap-1.5 px-2.5 py-2">
+ <span className="flex items-center gap-1.5 font-medium text-[13px]">
+ {secondaryTab.label}
+ </span>
+ </TabsTrigger>
+ </TabsList>
+ </Tabs>
+ </div>
+ )}
+
{/*
The detail body is a container-query grid:
- Left column caps at 80ch – matches the prose width inside, because
@@ -176,43 +205,64 @@ export function InboxDetailFrame({
of total width. Wider viewports just get larger side gutters.
*/}
<div className="@container mx-auto w-full max-w-[calc(160ch+5rem)] px-6 py-5 text-[13px]">
- <div className="grid @4xl:grid-cols-[minmax(0,80ch)_minmax(0,1fr)] grid-cols-1 gap-5">
+ {secondaryTab && activeTab === "secondary" ? (
<div className="flex min-w-0 flex-col gap-5">
- <DetailSection Icon={SummaryIcon} title={summarySection.title}>
- <SignalReportSummaryMarkdown
- content={report.summary}
- fallback="No summary yet – the agent is still investigating."
- variant="detail"
- pending={report.status === "in_progress"}
- />
- </DetailSection>
- {belowSummary}
+ {secondaryTab.content}
</div>
-
- <div className="flex min-w-0 flex-col gap-5">
- {hasEvidence && (
- <RightColumnSection
- Icon={EvidenceIcon}
- title={evidenceSection.title}
- rightSlot={
- <Text className="cursor-default select-none text-[11px] text-gray-10 tabular-nums">
- {evidenceCount} signal
- {evidenceCount === 1 ? "" : "s"}
- </Text>
- }
+ ) : (
+ <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">
+ <DetailSection
+ Icon={SummaryIcon}
+ title={summarySection.title}
+ collapsible
>
- {signals.length > 0 ? (
- <SignalsList signals={signals} />
- ) : (
- <SignalsListSkeleton count={evidenceCount} />
+ <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>
)}
- </RightColumnSection>
- )}
- {children}
+ </DetailSection>
+ {belowSummary}
+ </div>
+
+ <div className="flex min-w-0 flex-col gap-5">
+ {aboveEvidence}
+ {hasEvidence && (
+ <RightColumnSection
+ Icon={EvidenceIcon}
+ title={evidenceSection.title}
+ collapsible
+ rightSlot={
+ <span className="cursor-default select-none text-[11px] text-gray-10 tabular-nums">
+ {evidenceCount} signal
+ {evidenceCount === 1 ? "" : "s"}
+ </span>
+ }
+ >
+ {signals.length > 0 ? (
+ <SignalsList signals={signals} />
+ ) : (
+ <SignalsListSkeleton count={evidenceCount} />
+ )}
+ </RightColumnSection>
+ )}
+ {children}
+ </div>
</div>
- </div>
+ )}
{showDismiss && dismissDialog}
</div>
- </Flex>
+ </div>
);
}
diff --git a/products/desktop/packages/ui/src/features/inbox/components/InboxPageHeader.tsx b/products/desktop/packages/ui/src/features/inbox/components/InboxPageHeader.tsx
index 1217391dcc9a..0dc57adcd665 100644
--- a/products/desktop/packages/ui/src/features/inbox/components/InboxPageHeader.tsx
+++ b/products/desktop/packages/ui/src/features/inbox/components/InboxPageHeader.tsx
@@ -1,8 +1,10 @@
+import { RobotIcon } from "@phosphor-icons/react";
import {
type InboxTabCounts,
inboxScopeApplies,
inboxTabFromPath,
} from "@posthog/core/inbox/reportMembership";
+import { Button } from "@posthog/quill";
import { useBluebirdFlag } from "@posthog/ui/features/feature-flags/useBluebirdFlag";
import { InboxScopeSelect } from "@posthog/ui/features/inbox/components/InboxScopeSelect";
import {
@@ -11,6 +13,7 @@ import {
} from "@posthog/ui/features/inbox/components/InboxTabBar";
import {
PageHeader,
+ PageHeaderActions,
PageHeaderDescription,
PageHeaderFilters,
PageHeaderHeading,
@@ -18,13 +21,31 @@ import {
PageHeaderTitle,
PageHeaderTitleRow,
} from "@posthog/ui/primitives/PageHeader";
-import { Flex, Text } from "@radix-ui/themes";
-import { useRouterState } from "@tanstack/react-router";
+import { Link, useRouterState } from "@tanstack/react-router";
interface InboxPageHeaderProps {
counts: InboxTabCounts;
}
+/**
+ * Responder configuration lives at /code/agents, not in the inbox. The header
+ * carries this always-visible way there so the config surface stays one click
+ * away from the work it powers.
+ */
+function ConfigureAgentsButton() {
+ return (
+ <Button
+ variant="primary"
+ size="sm"
+ render={<Link to="/code/agents" />}
+ className="shrink-0"
+ >
+ <RobotIcon size={14} />
+ Configure agents
+ </Button>
+ );
+}
+
export function InboxPageHeader({ counts }: InboxPageHeaderProps) {
// The shared page header ships behind bluebird; everyone else keeps the
// header this page has always had. Delete the legacy branch when the flag
@@ -39,6 +60,9 @@ export function InboxPageHeader({ counts }: InboxPageHeaderProps) {
<PageHeaderHeading>
<PageHeaderTitleRow>
<PageHeaderTitle>Inbox</PageHeaderTitle>
+ <PageHeaderActions>
+ <ConfigureAgentsButton />
+ </PageHeaderActions>
</PageHeaderTitleRow>
<PageHeaderDescription>
Work done by your agents – pull requests, reports, and live runs.
@@ -58,20 +82,19 @@ export function InboxPageHeader({ counts }: InboxPageHeaderProps) {
function LegacyInboxPageHeader({ counts }: InboxPageHeaderProps) {
return (
- <Flex
- direction="column"
- gap="3"
- className="shrink-0 border-(--gray-5) border-b px-6 pt-5 pb-0"
- >
- <Flex direction="column" gap="0.5" className="cursor-default select-none">
- <Text className="font-bold text-[22px] text-gray-12 leading-tight tracking-tight">
- Inbox
- </Text>
- <Text className="max-w-3xl text-[12.5px] text-gray-11 leading-snug">
- Work done by your agents – pull requests, reports, and live runs.
- </Text>
- </Flex>
+ <div className="flex shrink-0 flex-col gap-3 border-(--gray-5) border-b px-6 pt-5 pb-0">
+ <div className="flex items-start justify-between gap-3">
+ <div className="flex cursor-default select-none flex-col gap-0.5">
+ <span className="font-bold text-[22px] text-gray-12 leading-tight tracking-tight">
+ Inbox
+ </span>
+ <span className="max-w-3xl text-[12.5px] text-gray-11 leading-snug">
+ Work done by your agents – pull requests, reports, and live runs.
+ </span>
+ </div>
+ <ConfigureAgentsButton />
+ </div>
<InboxTabBar counts={counts} />
- </Flex>
+ </div>
);
}
diff --git a/products/desktop/packages/ui/src/features/inbox/components/InboxReportListTab.tsx b/products/desktop/packages/ui/src/features/inbox/components/InboxReportListTab.tsx
index a81e86ca5112..74dde9ac36fd 100644
--- a/products/desktop/packages/ui/src/features/inbox/components/InboxReportListTab.tsx
+++ b/products/desktop/packages/ui/src/features/inbox/components/InboxReportListTab.tsx
@@ -27,7 +27,6 @@ import {
} from "@posthog/ui/features/inbox/hooks/useInboxBulkActions";
import { useInboxReportListSelection } from "@posthog/ui/features/inbox/hooks/useInboxReportListSelection";
import { useInboxReviewerScopeStore } from "@posthog/ui/features/inbox/stores/inboxReviewerScopeStore";
-import { Flex } from "@radix-ui/themes";
import {
type ComponentType,
Fragment,
@@ -167,18 +166,23 @@ export function InboxReportListTab({
const emptyTitle = resolveEmptyTitle(scope, emptyState);
const EmptyIcon = emptyState.Icon;
+ // `@container` makes the card layout respond to the list column's width
+ // (cards stack below their `@lg` breakpoint), not the window's.
+ const listShellClassName =
+ "@container mx-auto flex w-full max-w-4xl flex-col gap-4 px-6 py-4";
+
if (isLoading && scopedReports.length === 0) {
return (
- <Flex direction="column" gap="4" className="mx-auto max-w-4xl px-6 py-4">
+ <div className={listShellClassName}>
<InboxSearchFilterBar searchPlaceholder={searchPlaceholder} />
<CardSkeleton count={4} variant="cards" />
- </Flex>
+ </div>
);
}
return (
<>
- <Flex direction="column" gap="4" className="mx-auto max-w-4xl px-6 py-4">
+ <div className={listShellClassName}>
<InboxSearchFilterBar searchPlaceholder={searchPlaceholder} />
{selectedCount > 0 ? (
@@ -206,7 +210,7 @@ export function InboxReportListTab({
reports={matchingReports}
Wrapper={CardListWrapper}
>
- <Flex direction="column" gap="3">
+ <div className="flex flex-col gap-3">
{matchingReports.map((report) => (
<Card
key={report.id}
@@ -225,7 +229,7 @@ export function InboxReportListTab({
}
/>
))}
- </Flex>
+ </div>
</CardListContainer>
)}
<InboxLoadMore
@@ -235,7 +239,7 @@ export function InboxReportListTab({
/>
</>
)}
- </Flex>
+ </div>
{dismissReport && (
<DismissReportDialog
diff --git a/products/desktop/packages/ui/src/features/inbox/components/InboxTabBar.tsx b/products/desktop/packages/ui/src/features/inbox/components/InboxTabBar.tsx
index 21131e6d2991..bfda3e29c0a8 100644
--- a/products/desktop/packages/ui/src/features/inbox/components/InboxTabBar.tsx
+++ b/products/desktop/packages/ui/src/features/inbox/components/InboxTabBar.tsx
@@ -9,7 +9,6 @@ import {
} from "@posthog/core/inbox/reportMembership";
import { Tabs, TabsList, TabsTrigger } from "@posthog/quill";
import { InboxScopeSelect } from "@posthog/ui/features/inbox/components/InboxScopeSelect";
-import { Flex } from "@radix-ui/themes";
import { useNavigate, useRouterState } from "@tanstack/react-router";
interface InboxTabBarProps {
@@ -22,10 +21,10 @@ export function InboxTabBar({ counts }: InboxTabBarProps) {
const activeKey = inboxTabFromPath(pathname);
return (
- <Flex align="center" justify="between" className="min-w-0">
+ <div className="flex min-w-0 items-center justify-between gap-2">
<InboxTabs counts={counts} />
{inboxScopeApplies(activeKey) && <InboxScopeSelect />}
- </Flex>
+ </div>
);
}
@@ -35,9 +34,13 @@ export function InboxTabs({ counts }: InboxTabBarProps) {
const pathname = useRouterState({ select: (s) => s.location.pathname });
const activeKey = inboxTabFromPath(pathname);
+ // quill's TabsList is `inline-flex w-fit` with no wrap or scroll of its own,
+ // so at narrow widths the strip needs a scroll container or it overflows the
+ // header row.
return (
<Tabs
value={activeKey}
+ className="min-w-0 overflow-x-auto"
onValueChange={(value: string) => {
const key = value as InboxTabKey;
navigate({ to: INBOX_TAB_LIST_ROUTE[key] });
diff --git a/products/desktop/packages/ui/src/features/inbox/components/PrDiffIndicator.tsx b/products/desktop/packages/ui/src/features/inbox/components/PrDiffIndicator.tsx
index cc6485b192c0..00d614e9cf23 100644
--- a/products/desktop/packages/ui/src/features/inbox/components/PrDiffIndicator.tsx
+++ b/products/desktop/packages/ui/src/features/inbox/components/PrDiffIndicator.tsx
@@ -1,5 +1,3 @@
-import { Flex, Text, Tooltip } from "@radix-ui/themes";
-
export interface PrDiffIndicatorProps {
added: number;
removed: number;
@@ -26,24 +24,17 @@ export function PrDiffIndicator({
? `${files} file${files === 1 ? "" : "s"} changed`
: undefined;
- const indicator = (
- <Flex
- align="center"
- gap="1.5"
- className={`shrink-0 font-mono text-[12px] tabular-nums ${className}`}
+ return (
+ <span
+ className={`flex shrink-0 items-center gap-1.5 font-mono text-[12px] tabular-nums ${className}`}
+ title={fileLabel}
>
{added > 0 && (
- <Text className="font-medium text-(--green-11)">+{added}</Text>
+ <span className="font-medium text-(--green-11)">+{added}</span>
)}
{removed > 0 && (
- <Text className="font-medium text-(--red-11)">−{removed}</Text>
+ <span className="font-medium text-(--red-11)">−{removed}</span>
)}
- </Flex>
+ </span>
);
-
- if (!fileLabel) {
- return indicator;
- }
-
- return <Tooltip content={fileLabel}>{indicator}</Tooltip>;
}
diff --git a/products/desktop/packages/ui/src/features/inbox/components/PullRequestCard.stories.tsx b/products/desktop/packages/ui/src/features/inbox/components/PullRequestCard.stories.tsx
new file mode 100644
index 000000000000..5b4de5b06f37
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/inbox/components/PullRequestCard.stories.tsx
@@ -0,0 +1,118 @@
+import type {
+ SignalReport,
+ SignalReportArtefactsResponse,
+ SuggestedReviewersArtefact,
+} from "@posthog/shared/types";
+import type { Meta, StoryObj } from "@storybook/react";
+import type { ReactNode } from "react";
+import { PullRequestCardView } from "./PullRequestCard";
+
+const report = (overrides: Partial<SignalReport> = {}): SignalReport => ({
+ id: "story-pr-report",
+ title: "fix(product-tours): guard step anchors against removed DOM nodes",
+ summary:
+ "Users abandoning a tour mid-step leave the anchor detached, which crashes the next step render. The fix re-resolves anchors lazily.",
+ status: "ready",
+ total_weight: 60,
+ signal_count: 12,
+ created_at: "2026-08-01T10:00:00Z",
+ updated_at: "2026-08-06T10:00:00Z",
+ artefact_count: 2,
+ priority: "P1",
+ actionability: "immediately_actionable",
+ source_products: ["error_tracking"],
+ implementation_pr_url: "https://github.com/PostHog/posthog/pull/12345",
+ ...overrides,
+});
+
+const reviewersArtefact: SuggestedReviewersArtefact = {
+ id: "artefact-reviewers",
+ created_at: "2026-08-06T10:00:00Z",
+ type: "suggested_reviewers",
+ content: [
+ {
+ github_login: "example-reviewer",
+ github_name: "Example Reviewer",
+ relevant_commits: [],
+ user: null,
+ },
+ ],
+};
+
+const reviewers: SignalReportArtefactsResponse = {
+ results: [reviewersArtefact],
+ count: 1,
+};
+
+/**
+ * Cards read their breakpoint from an `@container` ancestor (the list shell in
+ * the app). Wide shows the rail layout, narrow the stacked layout.
+ */
+const containerAt = (width: number) => (Story: () => ReactNode) => (
+ <div className="@container" style={{ width }}>
+ <Story />
+ </div>
+);
+
+const meta: Meta<typeof PullRequestCardView> = {
+ title: "Inbox/PullRequestCard",
+ component: PullRequestCardView,
+ args: {
+ report: report(),
+ repoSlug: "PostHog/posthog",
+ artefacts: reviewers,
+ renderBody: (body, className) => <div className={className}>{body}</div>,
+ },
+ decorators: [containerAt(800)],
+};
+export default meta;
+
+type Story = StoryObj<typeof PullRequestCardView>;
+
+export const Wide: Story = {};
+
+/**
+ * A two-line title must start on the same line as the scope tag and wrap
+ * beneath it, not center vertically beside it.
+ */
+export const WrappingTitle: Story = {
+ args: {
+ report: report({
+ title:
+ "fix(product-tours): guard step anchors against removed DOM nodes so abandoned tours no longer crash the next step render",
+ }),
+ },
+};
+
+/** Below the `@lg` container breakpoint the card stacks and the rail border disappears. */
+export const Narrow: Story = {
+ decorators: [containerAt(420)],
+};
+
+export const NarrowWrappingTitle: Story = {
+ args: WrappingTitle.args,
+ decorators: [containerAt(420)],
+};
+
+export const Selected: Story = {
+ args: { isSelected: true },
+};
+
+export const DismissPending: Story = {
+ args: { isDismissPending: true },
+};
+
+/** No repo/artefact data yet: meta row collapses to what the report carries. */
+export const MinimalData: Story = {
+ args: {
+ report: report({
+ title: "Untitled pull request",
+ summary: null,
+ priority: null,
+ actionability: null,
+ source_products: [],
+ }),
+ repoSlug: null,
+ artefacts: null,
+ },
+};
diff --git a/products/desktop/packages/ui/src/features/inbox/components/PullRequestCard.tsx b/products/desktop/packages/ui/src/features/inbox/components/PullRequestCard.tsx
index b20765161c77..fadd7adf5c52 100644
--- a/products/desktop/packages/ui/src/features/inbox/components/PullRequestCard.tsx
+++ b/products/desktop/packages/ui/src/features/inbox/components/PullRequestCard.tsx
@@ -6,9 +6,19 @@ import {
parseConventionalCommitTitle,
parsePrUrl,
} from "@posthog/core/inbox/reportPresentation";
-import { Button, cn } from "@posthog/quill";
-import type { SignalReport } from "@posthog/shared/types";
+import { Button } from "@posthog/quill";
+import type {
+ SignalReport,
+ SignalReportArtefactsResponse,
+} from "@posthog/shared/types";
import { ConventionalCommitScopeTag } from "@posthog/ui/features/inbox/components/ConventionalCommitScopeTag";
+import {
+ InboxCardActions,
+ InboxCardTimestamp,
+ InboxCardTopRight,
+ inboxCardBodyClassName,
+ inboxCardClassName,
+} from "@posthog/ui/features/inbox/components/InboxCardChrome";
import { InboxCardSourceMeta } from "@posthog/ui/features/inbox/components/InboxCardSourceMeta";
import { InboxCardTitle } from "@posthog/ui/features/inbox/components/InboxCardTitle";
import { PrDiffStats } from "@posthog/ui/features/inbox/components/PrDiffStats";
@@ -18,9 +28,143 @@ import { ReportImplementationPrLink } from "@posthog/ui/features/inbox/component
import { useInboxReportDetailPrefetch } from "@posthog/ui/features/inbox/hooks/useInboxReportDetailPrefetch";
import { useInboxReportArtefacts } from "@posthog/ui/features/inbox/hooks/useInboxReports";
import { Button as UiButton } from "@posthog/ui/primitives/Button";
-import { Flex, Text } from "@radix-ui/themes";
import { Link, useNavigate } from "@tanstack/react-router";
-import type { MouseEvent } from "react";
+import type { HTMLAttributes, MouseEvent, ReactNode } from "react";
+
+export interface PullRequestCardViewProps {
+ report: SignalReport;
+ repoSlug?: string | null;
+ /** Resolved artefacts for the reviewer stack; null renders no avatars. */
+ artefacts: SignalReportArtefactsResponse | null;
+ isSelected?: boolean;
+ onDismiss?: () => void;
+ dismissDisabledReason?: string | null;
+ isDismissPending?: boolean;
+ onReview?: () => void;
+ /** Wraps the card body; the container passes the detail-route Link. */
+ renderBody: (body: ReactNode, className: string) => ReactNode;
+ rootProps?: HTMLAttributes<HTMLDivElement>;
+}
+
+/** Pure card; the container wires routing, prefetch, and artefact data. */
+export function PullRequestCardView({
+ report,
+ repoSlug,
+ artefacts,
+ isSelected = false,
+ onDismiss,
+ dismissDisabledReason = null,
+ isDismissPending = false,
+ onReview,
+ renderBody,
+ rootProps,
+}: PullRequestCardViewProps) {
+ const conventionalTitle = parseConventionalCommitTitle(report.title);
+ const cardTitle = displayConventionalCommitTitle(
+ report.title,
+ "Untitled pull request",
+ );
+ const headline = deriveHeadline(report.summary);
+
+ const body = (
+ <>
+ <PriorityMonogram priority={report.priority} />
+
+ <div className="flex min-w-0 flex-1 flex-col gap-1.5">
+ {/* Pad clear of the absolute PR pill while the title spans the full card width. */}
+ <div className="min-w-0 @lg:pr-0 pr-16">
+ <InboxCardTitle
+ tag={
+ conventionalTitle && (
+ <ConventionalCommitScopeTag
+ type={conventionalTitle.type}
+ scope={conventionalTitle.scope}
+ compact
+ />
+ )
+ }
+ >
+ {cardTitle}
+ </InboxCardTitle>
+ </div>
+
+ {headline && (
+ <span className="wrap-break-word line-clamp-2 min-w-0 text-[12.5px] text-gray-10 leading-snug">
+ {headline}
+ </span>
+ )}
+
+ <div className="flex min-w-0 flex-wrap items-center gap-2.5">
+ <InboxCardSourceMeta
+ repoSlug={repoSlug}
+ sourceProducts={report.source_products}
+ className=""
+ />
+ {report.implementation_pr_url && (
+ <PrDiffStats
+ prUrl={report.implementation_pr_url}
+ hideWhileLoading
+ />
+ )}
+ </div>
+
+ <InboxCardTimestamp
+ timestamp={report.updated_at ?? report.created_at}
+ />
+ </div>
+ </>
+ );
+
+ return (
+ <div className={inboxCardClassName({ isSelected })} {...rootProps}>
+ {report.implementation_pr_url && (
+ <InboxCardTopRight>
+ <ReportImplementationPrLink
+ prUrl={report.implementation_pr_url}
+ size="sm"
+ />
+ </InboxCardTopRight>
+ )}
+
+ {renderBody(body, inboxCardBodyClassName)}
+
+ <InboxCardActions>
+ <SuggestedReviewerAvatarStack
+ reportId={report.id}
+ artefacts={artefacts}
+ />
+ <UiButton
+ type="button"
+ variant="soft"
+ color="gray"
+ size="1"
+ aria-label="Archive this report"
+ tooltipContent="Archive this report"
+ disabled={dismissDisabledReason !== null || isDismissPending}
+ disabledReason={dismissDisabledReason}
+ loading={isDismissPending}
+ onClick={(event) => {
+ event.stopPropagation();
+ onDismiss?.();
+ }}
+ >
+ <ArchiveIcon size={14} />
+ </UiButton>
+ <Button
+ type="button"
+ variant="primary"
+ size="sm"
+ onClick={(event) => {
+ event.stopPropagation();
+ onReview?.();
+ }}
+ >
+ Review
+ </Button>
+ </InboxCardActions>
+ </div>
+ );
+}
interface PullRequestCardProps {
report: SignalReport;
@@ -58,118 +202,37 @@ export function PullRequestCard({
const repoSlug =
extractRepoSelectionRepository(artefactsResp?.results) ?? prRef?.repoSlug;
- const conventionalTitle = parseConventionalCommitTitle(report.title);
- const cardTitle = displayConventionalCommitTitle(
- report.title,
- "Untitled pull request",
- );
-
return (
- <div
- className={cn(
- "group flex w-full items-start gap-3 rounded-(--radius-2) border border-border bg-(--color-panel-solid) px-4 py-3.5 transition duration-150 hover:border-(--gray-6) hover:bg-(--gray-2) hover:shadow-sm",
- isSelected &&
- "border-(--accent-8) bg-(--accent-2) ring-(--accent-8) ring-2 ring-inset",
+ <PullRequestCardView
+ report={report}
+ repoSlug={repoSlug}
+ artefacts={artefactsResp ?? null}
+ isSelected={isSelected}
+ onDismiss={onDismiss}
+ dismissDisabledReason={dismissDisabledReason}
+ isDismissPending={isDismissPending}
+ onReview={() => {
+ prefetch();
+ navigate(detailRoute);
+ }}
+ rootProps={pointerHandlers}
+ renderBody={(body, className) => (
+ <Link
+ {...detailRoute}
+ preload="intent"
+ onClick={(event) => {
+ onRowClick?.(event);
+ if (event.metaKey || event.ctrlKey || event.shiftKey) {
+ event.preventDefault();
+ return;
+ }
+ prefetch();
+ }}
+ className={className}
+ >
+ {body}
+ </Link>
)}
- {...pointerHandlers}
- >
- <Link
- {...detailRoute}
- preload="intent"
- onClick={(event) => {
- onRowClick?.(event);
- if (event.metaKey || event.ctrlKey || event.shiftKey) {
- event.preventDefault();
- return;
- }
- prefetch();
- }}
- className="flex min-w-0 flex-1 items-start gap-3 text-left text-inherit no-underline focus-visible:outline-none"
- >
- <PriorityMonogram priority={report.priority} />
-
- <Flex direction="column" gap="1.5" className="min-w-0 flex-1">
- <Flex align="center" gap="1" wrap="wrap" className="min-w-0">
- {conventionalTitle && (
- <ConventionalCommitScopeTag
- type={conventionalTitle.type}
- scope={conventionalTitle.scope}
- compact
- />
- )}
- <InboxCardTitle>{cardTitle}</InboxCardTitle>
- </Flex>
-
- {(() => {
- const headline = deriveHeadline(report.summary);
- return headline ? (
- <Text className="wrap-break-word mt-0.5 line-clamp-2 text-[12.5px] text-gray-10 leading-snug">
- {headline}
- </Text>
- ) : null;
- })()}
-
- <InboxCardSourceMeta
- repoSlug={repoSlug}
- sourceProducts={report.source_products}
- />
- </Flex>
- </Link>
-
- <Flex
- align="center"
- className="gap-3.5 self-stretch border-border border-l pl-3"
- >
- <Flex align="center" gap="2" className="shrink-0">
- {report.implementation_pr_url && (
- <Flex direction="column" align="end" gap="1" className="shrink-0">
- <ReportImplementationPrLink
- prUrl={report.implementation_pr_url}
- size="sm"
- />
- <PrDiffStats
- prUrl={report.implementation_pr_url}
- hideWhileLoading
- />
- </Flex>
- )}
- <SuggestedReviewerAvatarStack
- reportId={report.id}
- artefacts={artefactsResp ?? null}
- />
- </Flex>
- <Flex align="center" className="shrink-0 gap-2.5">
- <UiButton
- type="button"
- variant="soft"
- color="gray"
- size="1"
- aria-label="Archive this report"
- tooltipContent="Archive this report"
- disabled={dismissDisabledReason !== null || isDismissPending}
- disabledReason={dismissDisabledReason}
- loading={isDismissPending}
- onClick={(event) => {
- event.stopPropagation();
- onDismiss();
- }}
- >
- <ArchiveIcon size={14} />
- </UiButton>
- <Button
- type="button"
- variant="primary"
- size="sm"
- onClick={(event) => {
- event.stopPropagation();
- prefetch();
- navigate(detailRoute);
- }}
- >
- Review
- </Button>
- </Flex>
- </Flex>
- </div>
+ />
);
}
diff --git a/products/desktop/packages/ui/src/features/inbox/components/PullRequestDetail.tsx b/products/desktop/packages/ui/src/features/inbox/components/PullRequestDetail.tsx
index a4667ec27d3d..e579c19d6843 100644
--- a/products/desktop/packages/ui/src/features/inbox/components/PullRequestDetail.tsx
+++ b/products/desktop/packages/ui/src/features/inbox/components/PullRequestDetail.tsx
@@ -8,11 +8,13 @@ import { parsePrUrl } from "@posthog/core/inbox/reportPresentation";
import { Button } from "@posthog/quill";
import type { SignalReport } from "@posthog/shared/types";
import { ReportActivitySection } from "@posthog/ui/features/inbox/components/detail/ReportActivitySection";
+import { ReportFeedbackFooter } from "@posthog/ui/features/inbox/components/detail/ReportFeedbackFooter";
import { InboxDetailFrame } from "@posthog/ui/features/inbox/components/InboxDetailFrame";
import { InboxMetaSeparator } from "@posthog/ui/features/inbox/components/InboxMetaRow";
import { InboxReportDetailGate } from "@posthog/ui/features/inbox/components/InboxReportDetailGate";
import { PrDiffStats } from "@posthog/ui/features/inbox/components/PrDiffStats";
import { ReportDetailActions } from "@posthog/ui/features/inbox/components/ReportDetailActions";
+import { ReportRefundAction } from "@posthog/ui/features/inbox/components/ReportRefundAction";
import { ReportTasksSection } from "@posthog/ui/features/inbox/components/ReportTasksSection";
import { SuggestedReviewersSection } from "@posthog/ui/features/inbox/components/SuggestedReviewersSection";
import { ReportImplementationPrLink } from "@posthog/ui/features/inbox/components/utils/ReportImplementationPrLink";
@@ -21,7 +23,6 @@ import { PrChecksSection } from "@posthog/ui/features/pr-review/PrChecksSection"
import { PrCommentsSection } from "@posthog/ui/features/pr-review/PrCommentsSection";
import { PrFilesChangedSection } from "@posthog/ui/features/pr-review/PrFilesChangedSection";
import { PrReviewActions } from "@posthog/ui/features/pr-review/PrReviewActions";
-import { Text } from "@radix-ui/themes";
interface PullRequestDetailProps {
reportId: string;
@@ -60,9 +61,9 @@ function PullRequestDetailContent({ report }: { report: SignalReport }) {
prRef ? (
<>
<span className="text-(--gray-8)">/</span>
- <Text className="font-mono text-[12px] text-gray-11">
+ <span className="font-mono text-[12px] text-gray-11">
{prRef.repoSlug}#{prRef.number}
- </Text>
+ </span>
</>
) : undefined
}
@@ -83,16 +84,6 @@ function PullRequestDetailContent({ report }: { report: SignalReport }) {
}
primaryAction={
<>
- <ReportDetailActions report={report} />
- <Button
- type="button"
- variant="outline"
- size="sm"
- onClick={() => copyInboxReportLink(report)}
- title="Copy a deep link to this report"
- >
- <CopyIcon size={12} />
- </Button>
{prRef && report.implementation_pr_url ? (
<Button
type="button"
@@ -112,26 +103,66 @@ function PullRequestDetailContent({ report }: { report: SignalReport }) {
<ArrowSquareOutIcon size={12} />
</Button>
) : null}
+ <ReportDetailActions report={report} />
+ <ReportRefundAction report={report} />
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => copyInboxReportLink(report)}
+ title="Copy a deep link to this report"
+ >
+ <CopyIcon size={12} />
+ </Button>
</>
}
summarySection={{ Icon: GitPullRequestIcon, title: "Summary" }}
+ secondaryTab={
+ prRef && report.implementation_pr_url
+ ? {
+ label: (
+ <>
+ Files changed
+ <PrDiffStats
+ prUrl={report.implementation_pr_url}
+ hideWhileLoading
+ />
+ </>
+ ),
+ content: (
+ <PrFilesChangedSection
+ prUrl={report.implementation_pr_url}
+ bare
+ />
+ ),
+ }
+ : undefined
+ }
belowSummary={
- prRef && report.implementation_pr_url ? (
- <>
- <PrFilesChangedSection prUrl={report.implementation_pr_url} />
- <PrCommentsSection prUrl={report.implementation_pr_url} />
- <PrChecksSection prUrl={report.implementation_pr_url} />
- <PrReviewActions prUrl={report.implementation_pr_url} />
- </>
- ) : undefined
+ <>
+ {prRef && report.implementation_pr_url && (
+ <>
+ <PrCommentsSection prUrl={report.implementation_pr_url} />
+ <PrReviewActions prUrl={report.implementation_pr_url} />
+ </>
+ )}
+ <ReportFeedbackFooter report={report} />
+ </>
}
evidenceSection={{ Icon: MagnifyingGlassIcon, title: "Evidence" }}
+ aboveEvidence={
+ <>
+ {prRef && report.implementation_pr_url && (
+ <PrChecksSection prUrl={report.implementation_pr_url} />
+ )}
+ <SuggestedReviewersSection report={report} />
+ </>
+ }
>
<ReportTasksSection report={report} />
- <SuggestedReviewersSection report={report} />
<ReportActivitySection
reportId={report.id}
- // The main column already lists every changed file, so the
+ // The Files changed tab already lists every changed file, so the
// per-commit diff toggle in the activity log is redundant here.
hideCommitDiffs={Boolean(prRef && report.implementation_pr_url)}
/>
diff --git a/products/desktop/packages/ui/src/features/inbox/components/RefundReportDialog.tsx b/products/desktop/packages/ui/src/features/inbox/components/RefundReportDialog.tsx
new file mode 100644
index 000000000000..bcc837900ba6
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/inbox/components/RefundReportDialog.tsx
@@ -0,0 +1,146 @@
+import {
+ Button,
+ Dialog,
+ DialogBody,
+ DialogClose,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ Label,
+ RadioGroup,
+ RadioGroupItem,
+ Textarea,
+} from "@posthog/quill";
+import type {
+ SignalReport,
+ SignalReportRefundReason,
+} from "@posthog/shared/types";
+import { useId, useState } from "react";
+
+const REFUND_REASON_OPTIONS: {
+ value: SignalReportRefundReason;
+ label: string;
+}[] = [
+ {
+ value: "pr_incorrect",
+ label: "The PR doesn't fix what the report describes",
+ },
+ { value: "pr_not_useful", label: "The PR works but is not useful to me" },
+ { value: "duplicate", label: "Duplicate of work already covered" },
+ { value: "other", label: "Something else…" },
+];
+
+export interface RefundReportDialogProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ report: SignalReport;
+ isSubmitting: boolean;
+ onConfirm: (result: {
+ reason: SignalReportRefundReason;
+ note: string;
+ }) => void;
+}
+
+export function RefundReportDialog({
+ open,
+ onOpenChange,
+ report,
+ isSubmitting,
+ onConfirm,
+}: RefundReportDialogProps) {
+ return (
+ <Dialog
+ open={open}
+ onOpenChange={(next) => {
+ // Don't let an Esc / backdrop dismiss abandon an in-flight refund.
+ if (!next && isSubmitting) return;
+ onOpenChange(next);
+ }}
+ >
+ <DialogContent className="sm:max-w-md" showCloseButton={!isSubmitting}>
+ <RefundReportDialogBody
+ report={report}
+ isSubmitting={isSubmitting}
+ onConfirm={onConfirm}
+ />
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+function RefundReportDialogBody({
+ report,
+ isSubmitting,
+ onConfirm,
+}: Omit<RefundReportDialogProps, "open" | "onOpenChange">) {
+ const [reason, setReason] = useState<SignalReportRefundReason | null>(null);
+ const [note, setNote] = useState("");
+ const fieldId = useId();
+
+ const title = report.title?.trim() ? report.title : "Untitled report";
+
+ return (
+ <>
+ <DialogHeader>
+ <DialogTitle>Refund the PR for "{title}"?</DialogTitle>
+ <DialogDescription>
+ You won't pay for this PR and it won't count toward your included PRs.
+ The report is archived as part of the refund and can't be restored.
+ </DialogDescription>
+ </DialogHeader>
+
+ <DialogBody>
+ <div className="flex flex-col gap-4">
+ <RadioGroup
+ value={reason ?? ""}
+ onValueChange={(value) =>
+ setReason(value as SignalReportRefundReason)
+ }
+ >
+ {REFUND_REASON_OPTIONS.map((option) => {
+ const id = `${fieldId}-${option.value}`;
+ return (
+ <div key={option.value} className="flex items-center gap-2">
+ <RadioGroupItem value={option.value} id={id} />
+ <Label htmlFor={id} className="font-normal">
+ {option.label}
+ </Label>
+ </div>
+ );
+ })}
+ </RadioGroup>
+
+ <Textarea
+ value={note}
+ onChange={(event) => setNote(event.target.value)}
+ placeholder="Optional: helps us review refunds"
+ rows={3}
+ maxLength={4000}
+ disabled={isSubmitting}
+ />
+ </div>
+ </DialogBody>
+
+ <DialogFooter>
+ <DialogClose
+ render={
+ <Button variant="outline" size="sm" disabled={isSubmitting} />
+ }
+ >
+ Cancel
+ </DialogClose>
+ <Button
+ variant="primary"
+ size="sm"
+ disabled={!reason || isSubmitting}
+ loading={isSubmitting}
+ onClick={() => reason && onConfirm({ reason, note: note.trim() })}
+ >
+ Refund
+ </Button>
+ </DialogFooter>
+ </>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/inbox/components/ReportCard.stories.tsx b/products/desktop/packages/ui/src/features/inbox/components/ReportCard.stories.tsx
new file mode 100644
index 000000000000..fa2a446127bd
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/inbox/components/ReportCard.stories.tsx
@@ -0,0 +1,102 @@
+import type { SignalReport } from "@posthog/shared/types";
+import type { Meta, StoryObj } from "@storybook/react";
+import type { ReactNode } from "react";
+import { ReportCardView } from "./ReportCard";
+
+const report = (overrides: Partial<SignalReport> = {}): SignalReport => ({
+ id: "story-report",
+ title: "fix(replay): buffer underruns stall playback on long sessions",
+ summary:
+ "Playback stalls at snapshot gaps longer than the buffer window. Several long sessions this week hit the stall within the first minute.",
+ status: "ready",
+ total_weight: 40,
+ signal_count: 7,
+ created_at: "2026-08-01T10:00:00Z",
+ updated_at: "2026-08-06T10:00:00Z",
+ artefact_count: 1,
+ priority: "P2",
+ actionability: "immediately_actionable",
+ is_suggested_reviewer: true,
+ source_products: ["session_replay"],
+ ...overrides,
+});
+
+const containerAt = (width: number) => (Story: () => ReactNode) => (
+ <div className="@container" style={{ width }}>
+ <Story />
+ </div>
+);
+
+const meta: Meta<typeof ReportCardView> = {
+ title: "Inbox/ReportCard",
+ component: ReportCardView,
+ args: {
+ report: report(),
+ artefacts: null,
+ renderBody: (body, className) => <div className={className}>{body}</div>,
+ },
+ decorators: [containerAt(800)],
+};
+export default meta;
+
+type Story = StoryObj<typeof ReportCardView>;
+
+export const Wide: Story = {};
+
+/** Long conventional-commit title wraps under the inline scope tag. */
+export const WrappingTitle: Story = {
+ args: {
+ report: report({
+ title:
+ "fix(replay): buffer underruns stall playback on long sessions when the snapshot gap exceeds the prefetch window on slow connections",
+ }),
+ },
+};
+
+/** Below the `@lg` container breakpoint the card stacks and the rail border disappears. */
+export const Narrow: Story = {
+ decorators: [containerAt(420)],
+};
+
+/** Still-researching report: no headline yet, dimmed status. */
+export const Pending: Story = {
+ args: {
+ report: report({
+ status: "in_progress",
+ summary: null,
+ actionability: null,
+ priority: null,
+ }),
+ },
+};
+
+/** Archived report: dimmed, restore-only rail, dismissal reason chip. */
+export const Archived: Story = {
+ args: {
+ variant: "archived",
+ report: report({
+ status: "suppressed",
+ dismissal_reason: "analysis_wrong",
+ dismissal_note: "Known issue, tracked elsewhere.",
+ }),
+ },
+};
+
+/** Resolved report: terminal, reference-only, no actions rail at all. */
+export const Resolved: Story = {
+ args: {
+ variant: "archived",
+ report: report({ status: "resolved" }),
+ },
+};
+
+export const NarrowArchived: Story = {
+ args: {
+ variant: "archived",
+ report: report({
+ status: "suppressed",
+ dismissal_reason: "analysis_wrong",
+ }),
+ },
+ decorators: [containerAt(420)],
+};
diff --git a/products/desktop/packages/ui/src/features/inbox/components/ReportCard.tsx b/products/desktop/packages/ui/src/features/inbox/components/ReportCard.tsx
index 3cdfbbe2d93b..136ebcf88b58 100644
--- a/products/desktop/packages/ui/src/features/inbox/components/ReportCard.tsx
+++ b/products/desktop/packages/ui/src/features/inbox/components/ReportCard.tsx
@@ -9,10 +9,19 @@ import {
displayConventionalCommitTitle,
parseConventionalCommitTitle,
} from "@posthog/core/inbox/reportPresentation";
-import { Button, cn } from "@posthog/quill";
+import { Button } from "@posthog/quill";
import { dismissalReasonLabel } from "@posthog/shared/dismissalReasons";
-import type { SignalReport } from "@posthog/shared/types";
+import type {
+ SignalReport,
+ SignalReportArtefactsResponse,
+} from "@posthog/shared/types";
import { ConventionalCommitScopeTag } from "@posthog/ui/features/inbox/components/ConventionalCommitScopeTag";
+import {
+ InboxCardActions,
+ InboxCardTimestamp,
+ inboxCardBodyClassName,
+ inboxCardClassName,
+} from "@posthog/ui/features/inbox/components/InboxCardChrome";
import { InboxCardSourceMeta } from "@posthog/ui/features/inbox/components/InboxCardSourceMeta";
import { InboxCardTitle } from "@posthog/ui/features/inbox/components/InboxCardTitle";
import { PriorityMonogram } from "@posthog/ui/features/inbox/components/PriorityMonogram";
@@ -25,21 +34,25 @@ import { hasKnownSourceProduct } from "@posthog/ui/features/inbox/components/uti
import { useInboxReportDetailPrefetch } from "@posthog/ui/features/inbox/hooks/useInboxReportDetailPrefetch";
import { useInboxReportArtefacts } from "@posthog/ui/features/inbox/hooks/useInboxReports";
import { Button as UiButton } from "@posthog/ui/primitives/Button";
-import { Flex, Text } from "@radix-ui/themes";
import { Link, useNavigate } from "@tanstack/react-router";
-import type { MouseEvent } from "react";
+import type { HTMLAttributes, MouseEvent, ReactNode } from "react";
-interface BaseReportCardProps {
+interface ReportCardViewBaseProps {
report: SignalReport;
isSelected?: boolean;
- onRowClick?: (event: MouseEvent) => void;
+ /** Wraps the card body; the container passes the detail-route Link. */
+ renderBody: (body: ReactNode, className: string) => ReactNode;
+ rootProps?: HTMLAttributes<HTMLDivElement>;
}
-interface DefaultReportCardProps extends BaseReportCardProps {
+interface DefaultReportCardViewProps extends ReportCardViewBaseProps {
variant?: "default";
- onDismiss: () => void;
+ repoSlug?: string | null;
+ artefacts: SignalReportArtefactsResponse | null;
+ onDismiss?: () => void;
dismissDisabledReason?: string | null;
isDismissPending?: boolean;
+ onReview?: () => void;
}
/**
@@ -48,6 +61,254 @@ interface DefaultReportCardProps extends BaseReportCardProps {
* the metadata row swaps live badges for the archive date + dismissal reason,
* and the detail link points at the read-only archived view.
*/
+interface ArchivedReportCardViewProps extends ReportCardViewBaseProps {
+ variant: "archived";
+ onRestore?: () => void;
+ isRestorePending?: boolean;
+}
+
+export type ReportCardViewProps =
+ | DefaultReportCardViewProps
+ | ArchivedReportCardViewProps;
+
+export function ReportCardView(props: ReportCardViewProps) {
+ const { report, isSelected = false, renderBody, rootProps } = props;
+ const isArchived = props.variant === "archived";
+ // Resolved reports are terminal (their implementation PR merged): shown in the
+ // Archive tab for reference, badged as resolved, with no restore action.
+ const isResolved = report.status === "resolved";
+ const isReady = report.status === "ready";
+
+ const conventionalTitle = parseConventionalCommitTitle(report.title);
+ const cardTitle = displayConventionalCommitTitle(
+ report.title,
+ "Untitled report",
+ );
+ const headline = deriveHeadline(report.summary);
+ const hasSource = hasKnownSourceProduct(report.source_products);
+ const reasonLabel =
+ isArchived && report.dismissal_reason
+ ? dismissalReasonLabel(report.dismissal_reason)
+ : null;
+ const dismissalNote = report.dismissal_note?.trim() || null;
+ const updatedAtRaw = report.updated_at ?? report.created_at;
+ const archivedDate = updatedAtRaw ? new Date(updatedAtRaw) : null;
+ const archivedLabel =
+ archivedDate && !Number.isNaN(archivedDate.getTime())
+ ? archivedDate.toLocaleDateString(undefined, {
+ month: "short",
+ day: "numeric",
+ })
+ : null;
+
+ const hasMetadata = isArchived
+ ? hasSource || !!archivedLabel || !!reasonLabel || isResolved
+ : (props.repoSlug ?? null) !== null ||
+ hasSource ||
+ !isReady ||
+ report.actionability != null ||
+ report.is_suggested_reviewer === true ||
+ report.signal_count > 0;
+
+ const body = (
+ <>
+ <PriorityMonogram priority={report.priority} />
+
+ <div className="flex min-w-0 flex-1 flex-col gap-1.5">
+ <div className="min-w-0">
+ <InboxCardTitle
+ tag={
+ conventionalTitle && (
+ <ConventionalCommitScopeTag
+ type={conventionalTitle.type}
+ scope={conventionalTitle.scope}
+ compact
+ />
+ )
+ }
+ >
+ {cardTitle}
+ </InboxCardTitle>
+ </div>
+
+ {isArchived ? (
+ headline && (
+ <span className="wrap-break-word line-clamp-2 min-w-0 text-[12.5px] text-gray-10 leading-snug">
+ {headline}
+ </span>
+ )
+ ) : (
+ <div className={isReady ? "min-w-0" : "min-w-0 opacity-80"}>
+ {headline ? (
+ <span className="wrap-break-word line-clamp-2 text-[12.5px] text-gray-10 leading-snug">
+ {headline}
+ </span>
+ ) : (
+ <SignalReportSummaryMarkdown
+ content={report.summary}
+ fallback="No summary yet. Still collecting context."
+ variant="list"
+ pending={!isReady}
+ />
+ )}
+ </div>
+ )}
+
+ {hasMetadata && (
+ <div className="mt-1 flex min-w-0 flex-wrap items-center gap-2.5">
+ <InboxCardSourceMeta
+ repoSlug={isArchived ? null : (props.repoSlug ?? null)}
+ sourceProducts={report.source_products}
+ className=""
+ />
+ {isArchived ? (
+ <>
+ {archivedLabel && (
+ <span className="text-[12px] text-gray-10">
+ {isResolved ? "Resolved" : "Archived"} {archivedLabel}
+ </span>
+ )}
+ {isResolved ? (
+ <SignalReportStatusBadge status={report.status} />
+ ) : (
+ reasonLabel && (
+ <span
+ className="max-w-full truncate rounded-(--radius-1) bg-(--gray-3) px-1.5 py-0.5 text-[11px] text-gray-11"
+ title={
+ dismissalNote
+ ? `${reasonLabel}: ${dismissalNote}`
+ : reasonLabel
+ }
+ >
+ {reasonLabel}
+ </span>
+ )
+ )}
+ </>
+ ) : (
+ <>
+ {(!isReady || !report.actionability) && (
+ <SignalReportStatusBadge status={report.status} />
+ )}
+ {report.actionability && (
+ <SignalReportActionabilityBadge
+ actionability={report.actionability}
+ />
+ )}
+ {report.is_suggested_reviewer && <ForYouBadge />}
+ {report.signal_count > 0 && (
+ <span className="flex items-center gap-1 text-[12px] text-gray-10">
+ <LightningIcon size={11} />
+ <span className="tabular-nums">
+ {report.signal_count} signal
+ {report.signal_count !== 1 ? "s" : ""}
+ </span>
+ </span>
+ )}
+ </>
+ )}
+ </div>
+ )}
+
+ {!isArchived && (
+ <InboxCardTimestamp
+ timestamp={report.updated_at ?? report.created_at}
+ />
+ )}
+ </div>
+ </>
+ );
+
+ // A refunded/resolved archived report carries no actions; skip the rail (and
+ // its divider) entirely rather than render an empty bordered column.
+ const actions = isArchived ? (
+ isResolved ? null : (
+ <UiButton
+ type="button"
+ variant="soft"
+ color="gray"
+ size="1"
+ aria-label="Restore this report to the inbox"
+ tooltipContent="Restore to inbox"
+ loading={props.isRestorePending}
+ disabled={props.isRestorePending}
+ onClick={(event) => {
+ event.stopPropagation();
+ props.onRestore?.();
+ }}
+ >
+ <ArrowCounterClockwiseIcon size={14} />
+ Restore
+ </UiButton>
+ )
+ ) : (
+ <>
+ <SuggestedReviewerAvatarStack
+ reportId={report.id}
+ artefacts={props.artefacts}
+ />
+ <UiButton
+ type="button"
+ variant="soft"
+ color="gray"
+ size="1"
+ aria-label="Archive this report"
+ tooltipContent="Archive this report"
+ disabled={
+ (props.dismissDisabledReason ?? null) !== null ||
+ props.isDismissPending
+ }
+ disabledReason={props.dismissDisabledReason}
+ loading={props.isDismissPending}
+ onClick={(event) => {
+ event.stopPropagation();
+ props.onDismiss?.();
+ }}
+ >
+ <ArchiveIcon size={14} />
+ </UiButton>
+ <Button
+ type="button"
+ variant="primary"
+ size="sm"
+ onClick={(event) => {
+ event.stopPropagation();
+ props.onReview?.();
+ }}
+ >
+ Review
+ </Button>
+ </>
+ );
+
+ return (
+ <div
+ className={inboxCardClassName({
+ dashed: true,
+ isSelected: !isArchived && isSelected,
+ dimmed: isArchived,
+ })}
+ {...rootProps}
+ >
+ {renderBody(body, inboxCardBodyClassName)}
+ {actions && <InboxCardActions>{actions}</InboxCardActions>}
+ </div>
+ );
+}
+
+interface BaseReportCardProps {
+ report: SignalReport;
+ isSelected?: boolean;
+ onRowClick?: (event: MouseEvent) => void;
+}
+
+interface DefaultReportCardProps extends BaseReportCardProps {
+ variant?: "default";
+ onDismiss: () => void;
+ dismissDisabledReason?: string | null;
+ isDismissPending?: boolean;
+}
+
interface ArchivedReportCardProps extends BaseReportCardProps {
variant: "archived";
onRestore: () => void;
@@ -59,9 +320,6 @@ export type ReportCardProps = DefaultReportCardProps | ArchivedReportCardProps;
export function ReportCard(props: ReportCardProps) {
const { report, isSelected = false, onRowClick } = props;
const isArchived = props.variant === "archived";
- // Resolved reports are terminal (their implementation PR merged): shown in the
- // Archive tab for reference, badged as resolved, with no restore action.
- const isResolved = report.status === "resolved";
const detailRoute = isArchived
? {
@@ -87,247 +345,54 @@ export function ReportCard(props: ReportCardProps) {
const repoSlug = isArchived
? null
: extractRepoSelectionRepository(artefactsResp?.results);
- const hasSource = hasKnownSourceProduct(report.source_products);
- const updatedAtRaw = report.updated_at ?? report.created_at;
- const updatedAtDate = updatedAtRaw ? new Date(updatedAtRaw) : null;
- const updatedAtLabel =
- updatedAtDate && !Number.isNaN(updatedAtDate.getTime())
- ? updatedAtDate.toLocaleDateString(undefined, {
- month: "short",
- day: "numeric",
- })
- : null;
- const isReady = report.status === "ready";
- const conventionalTitle = parseConventionalCommitTitle(report.title);
- const cardTitle = displayConventionalCommitTitle(
- report.title,
- "Untitled report",
- );
- const headline = deriveHeadline(report.summary);
- const reasonLabel =
- isArchived && report.dismissal_reason
- ? dismissalReasonLabel(report.dismissal_reason)
- : null;
- const dismissalNote = report.dismissal_note?.trim() || null;
- const openDetail = () => {
- prefetch();
- navigate(detailRoute);
- };
-
- const hasMetadata = isArchived
- ? !!hasSource || !!updatedAtLabel || !!reasonLabel || isResolved
- : !!repoSlug ||
- hasSource ||
- !isReady ||
- report.actionability != null ||
- report.is_suggested_reviewer === true;
-
- return (
- <div
- className={cn(
- "group flex w-full items-stretch gap-3 rounded-(--radius-2) border border-(--gray-6) border-dashed bg-(--color-panel-solid) px-4 py-3.5 transition duration-150 hover:border-(--gray-7) hover:bg-(--gray-2)",
- isArchived ? "opacity-90" : "hover:shadow-sm",
- !isArchived &&
- isSelected &&
- "border-(--accent-8) bg-(--accent-2) ring-(--accent-8) ring-2 ring-inset",
- )}
- {...pointerHandlers}
+ const renderBody = (body: ReactNode, className: string) => (
+ <Link
+ {...detailRoute}
+ preload="intent"
+ onClick={(event) => {
+ onRowClick?.(event);
+ if (event.metaKey || event.ctrlKey || event.shiftKey) {
+ event.preventDefault();
+ return;
+ }
+ prefetch();
+ }}
+ className={className}
>
- <Link
- {...detailRoute}
- preload="intent"
- onClick={(event) => {
- onRowClick?.(event);
- if (event.metaKey || event.ctrlKey || event.shiftKey) {
- event.preventDefault();
- return;
- }
- prefetch();
- }}
- className="flex min-w-0 flex-1 items-start gap-3 text-left text-inherit no-underline focus-visible:outline-none"
- >
- <PriorityMonogram priority={report.priority} />
-
- <Flex direction="column" gap="1.5" className="min-w-0 flex-1">
- <Flex align="center" gap="1" wrap="wrap" className="min-w-0">
- {conventionalTitle && (
- <ConventionalCommitScopeTag
- type={conventionalTitle.type}
- scope={conventionalTitle.scope}
- compact
- />
- )}
- <InboxCardTitle>{cardTitle}</InboxCardTitle>
- </Flex>
-
- {isArchived ? (
- headline && (
- <Text className="wrap-break-word mt-0.5 line-clamp-2 text-[12.5px] text-gray-10 leading-snug">
- {headline}
- </Text>
- )
- ) : (
- <div
- className={
- isReady ? "mt-0.5 min-w-0" : "mt-0.5 min-w-0 opacity-80"
- }
- >
- {headline ? (
- <Text className="wrap-break-word line-clamp-2 text-[12.5px] text-gray-10 leading-snug">
- {headline}
- </Text>
- ) : (
- <SignalReportSummaryMarkdown
- content={report.summary}
- fallback="No summary yet – still collecting context."
- variant="list"
- pending={!isReady}
- />
- )}
- </div>
- )}
-
- {hasMetadata ? (
- <Flex align="center" wrap="wrap" className="mt-1.5 min-w-0 gap-2.5">
- <InboxCardSourceMeta
- repoSlug={repoSlug}
- sourceProducts={report.source_products}
- className=""
- />
- {isArchived ? (
- <>
- {updatedAtLabel && (
- <Text className="text-[12px] text-gray-10">
- {isResolved ? "Resolved" : "Archived"} {updatedAtLabel}
- </Text>
- )}
- {isResolved ? (
- <SignalReportStatusBadge status={report.status} />
- ) : (
- reasonLabel && (
- <Text
- className="max-w-full truncate rounded-(--radius-1) bg-(--gray-3) px-1.5 py-0.5 text-[11px] text-gray-11"
- title={
- dismissalNote
- ? `${reasonLabel} — ${dismissalNote}`
- : reasonLabel
- }
- >
- {reasonLabel}
- </Text>
- )
- )}
- </>
- ) : (
- <>
- {(!isReady || !report.actionability) && (
- <SignalReportStatusBadge status={report.status} />
- )}
- {report.actionability && (
- <SignalReportActionabilityBadge
- actionability={report.actionability}
- />
- )}
- {report.is_suggested_reviewer && <ForYouBadge />}
- </>
- )}
- </Flex>
- ) : null}
- </Flex>
- </Link>
-
- <Flex
- direction="column"
- align="end"
- justify="between"
- className="shrink-0 border-border border-l pl-3"
- >
- {props.variant === "archived" ? (
- // Resolved reports are terminal — reference-only, no restore action.
- isResolved ? null : (
- <UiButton
- type="button"
- variant="soft"
- color="gray"
- size="1"
- aria-label="Restore this report to the inbox"
- tooltipContent="Restore to inbox"
- loading={props.isRestorePending}
- disabled={props.isRestorePending}
- onClick={(event) => {
- event.stopPropagation();
- props.onRestore();
- }}
- >
- <ArrowCounterClockwiseIcon size={14} />
- Restore
- </UiButton>
- )
- ) : (
- <>
- {updatedAtLabel && (
- <Text className="shrink-0 text-[12px] text-gray-10 tabular-nums">
- {updatedAtLabel}
- </Text>
- )}
+ {body}
+ </Link>
+ );
- <Flex align="center" className="my-auto gap-3.5">
- <Flex align="center" className="shrink-0">
- <SuggestedReviewerAvatarStack
- reportId={report.id}
- artefacts={artefactsResp ?? null}
- />
- </Flex>
- <Flex align="center" className="shrink-0 gap-2.5">
- <UiButton
- type="button"
- variant="soft"
- color="gray"
- size="1"
- aria-label="Archive this report"
- tooltipContent="Archive this report"
- disabled={
- (props.dismissDisabledReason ?? null) !== null ||
- props.isDismissPending
- }
- disabledReason={props.dismissDisabledReason}
- loading={props.isDismissPending}
- onClick={(event) => {
- event.stopPropagation();
- props.onDismiss();
- }}
- >
- <ArchiveIcon size={14} />
- </UiButton>
- <Button
- type="button"
- variant="primary"
- size="sm"
- onClick={(event) => {
- event.stopPropagation();
- openDetail();
- }}
- >
- Review
- </Button>
- </Flex>
- </Flex>
- </>
- )}
+ if (props.variant === "archived") {
+ return (
+ <ReportCardView
+ variant="archived"
+ report={report}
+ isSelected={isSelected}
+ onRestore={props.onRestore}
+ isRestorePending={props.isRestorePending}
+ renderBody={renderBody}
+ rootProps={pointerHandlers}
+ />
+ );
+ }
- <Flex
- align="center"
- gap="1"
- className="shrink-0 text-[12px] text-gray-10"
- >
- <LightningIcon size={11} />
- <span className="tabular-nums">
- {report.signal_count} signal
- {report.signal_count !== 1 ? "s" : ""}
- </span>
- </Flex>
- </Flex>
- </div>
+ return (
+ <ReportCardView
+ report={report}
+ isSelected={isSelected}
+ repoSlug={repoSlug}
+ artefacts={artefactsResp ?? null}
+ onDismiss={props.onDismiss}
+ dismissDisabledReason={props.dismissDisabledReason}
+ isDismissPending={props.isDismissPending}
+ onReview={() => {
+ prefetch();
+ navigate(detailRoute);
+ }}
+ renderBody={renderBody}
+ rootProps={pointerHandlers}
+ />
);
}
diff --git a/products/desktop/packages/ui/src/features/inbox/components/ReportDetail.tsx b/products/desktop/packages/ui/src/features/inbox/components/ReportDetail.tsx
index 6abbb60f38af..9ca41fa44993 100644
--- a/products/desktop/packages/ui/src/features/inbox/components/ReportDetail.tsx
+++ b/products/desktop/packages/ui/src/features/inbox/components/ReportDetail.tsx
@@ -58,12 +58,12 @@ function ReportDetailContent({ report }: { report: SignalReport }) {
</>
}
summarySection={{ Icon: FileTextIcon, title: "Summary" }}
+ belowSummary={<ReportFeedbackFooter report={report} />}
evidenceSection={{ Icon: MagnifyingGlassIcon, title: "Evidence" }}
+ aboveEvidence={<SuggestedReviewersSection report={report} />}
>
<ReportTasksSection report={report} />
- <SuggestedReviewersSection report={report} />
<ReportActivitySection reportId={report.id} />
- <ReportFeedbackFooter report={report} />
</InboxDetailFrame>
);
}
diff --git a/products/desktop/packages/ui/src/features/inbox/components/ReportRefundAction.tsx b/products/desktop/packages/ui/src/features/inbox/components/ReportRefundAction.tsx
new file mode 100644
index 000000000000..d1d58d682e8d
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/inbox/components/ReportRefundAction.tsx
@@ -0,0 +1,47 @@
+import { ReceiptIcon } from "@phosphor-icons/react";
+import type { SignalReport } from "@posthog/shared/types";
+import { RefundReportDialog } from "@posthog/ui/features/inbox/components/RefundReportDialog";
+import { useRefundReport } from "@posthog/ui/features/inbox/hooks/useRefundReport";
+import { Button } from "@posthog/ui/primitives/Button";
+import { useState } from "react";
+
+/**
+ * Refund control for a report's billed PR, shown in the detail action row.
+ * Renders nothing unless the report is refund-eligible (flag on, billable PR,
+ * not already refunded).
+ */
+export function ReportRefundAction({ report }: { report: SignalReport }) {
+ const { canRefund, disabledReason, mutation } = useRefundReport(report);
+ const [open, setOpen] = useState(false);
+
+ if (!canRefund) {
+ return null;
+ }
+
+ return (
+ <>
+ <Button
+ type="button"
+ variant="soft"
+ color="gray"
+ size="1"
+ disabled={disabledReason !== null}
+ disabledReason={disabledReason}
+ onClick={() => setOpen(true)}
+ tooltipContent="Refund this PR and archive the report"
+ >
+ <ReceiptIcon size={14} />
+ Refund
+ </Button>
+ <RefundReportDialog
+ open={open}
+ onOpenChange={setOpen}
+ report={report}
+ isSubmitting={mutation.isPending}
+ onConfirm={(input) =>
+ mutation.mutate(input, { onSuccess: () => setOpen(false) })
+ }
+ />
+ </>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/inbox/components/ReportTasksSection.tsx b/products/desktop/packages/ui/src/features/inbox/components/ReportTasksSection.tsx
index 905d6bb3a427..5098de0338e1 100644
--- a/products/desktop/packages/ui/src/features/inbox/components/ReportTasksSection.tsx
+++ b/products/desktop/packages/ui/src/features/inbox/components/ReportTasksSection.tsx
@@ -21,7 +21,7 @@ export function ReportTasksSection({ report }: ReportTasksSectionProps) {
if (!reportTasks || reportTasks.length === 0) return null;
return (
- <RightColumnSection Icon={TerminalIcon} title="Runs">
+ <RightColumnSection Icon={TerminalIcon} title="Runs" collapsible>
<Flex direction="column" gap="0.5">
{reportTasks.map(({ task, purposeLabel }) => (
<TaskRow
diff --git a/products/desktop/packages/ui/src/features/inbox/components/RightColumnSection.tsx b/products/desktop/packages/ui/src/features/inbox/components/RightColumnSection.tsx
index afc6454df877..8677223e8bea 100644
--- a/products/desktop/packages/ui/src/features/inbox/components/RightColumnSection.tsx
+++ b/products/desktop/packages/ui/src/features/inbox/components/RightColumnSection.tsx
@@ -1,43 +1,13 @@
-import type { IconProps } from "@phosphor-icons/react";
-import { Flex, Text } from "@radix-ui/themes";
-import type { ComponentType, ReactNode } from "react";
-
-interface RightColumnSectionProps {
- Icon: ComponentType<IconProps>;
- title: string;
- rightSlot?: ReactNode;
- children: ReactNode;
-}
+import {
+ DetailSection,
+ type DetailSectionProps,
+} from "@posthog/ui/features/inbox/components/DetailSection";
/**
- * Slim caption header used by every section in the detail-view right column.
- * Smaller and lighter than `DetailSection` (no spanning divider) so the
- * side column reads as supporting detail rather than competing with the
- * main Summary on the left.
+ * Right-column sections share the main column's card chrome so the detail
+ * view reads as one card system. Kept as its own export so the two columns
+ * can diverge again without touching every consumer.
*/
-export function RightColumnSection({
- Icon,
- title,
- rightSlot,
- children,
-}: RightColumnSectionProps) {
- return (
- <Flex direction="column" gap="2">
- <Flex
- align="center"
- justify="between"
- gap="2"
- className="cursor-default select-none text-gray-10"
- >
- <Flex align="center" gap="2">
- <Icon size={12} className="shrink-0" />
- <Text className="font-medium text-[11px] uppercase tracking-[0.06em]">
- {title}
- </Text>
- </Flex>
- {rightSlot && <div className="shrink-0">{rightSlot}</div>}
- </Flex>
- <div>{children}</div>
- </Flex>
- );
+export function RightColumnSection(props: DetailSectionProps) {
+ return <DetailSection {...props} />;
}
diff --git a/products/desktop/packages/ui/src/features/inbox/components/RunsTab.tsx b/products/desktop/packages/ui/src/features/inbox/components/RunsTab.tsx
index 8e4b41279f2e..e14858bd71f7 100644
--- a/products/desktop/packages/ui/src/features/inbox/components/RunsTab.tsx
+++ b/products/desktop/packages/ui/src/features/inbox/components/RunsTab.tsx
@@ -15,7 +15,6 @@ import { AgentRunCard } from "@posthog/ui/features/inbox/components/AgentRunCard
import { CardSkeleton } from "@posthog/ui/features/inbox/components/CardSkeleton";
import { useInboxAllReports } from "@posthog/ui/features/inbox/hooks/useInboxAllReports";
import { useInboxReviewerScopeStore } from "@posthog/ui/features/inbox/stores/inboxReviewerScopeStore";
-import { Flex, Text } from "@radix-ui/themes";
import { useMemo, useState } from "react";
const RECENTLY_FINISHED_LIMIT = 10;
@@ -73,12 +72,12 @@ export function RunsTab() {
if (isLoading && scopedReports.length === 0) {
return (
- <Flex direction="column" gap="4" className="mx-auto max-w-3xl px-6 py-4">
- <Flex direction="column" gap="2">
+ <div className="@container mx-auto flex w-full max-w-3xl flex-col gap-4 px-6 py-4">
+ <div className="flex flex-col gap-2">
<span className="h-4 w-28 animate-pulse rounded bg-(--gray-3)" />
<CardSkeleton count={3} variant="rows" />
- </Flex>
- </Flex>
+ </div>
+ </div>
);
}
@@ -86,7 +85,7 @@ export function RunsTab() {
queuedRuns.length > 0 || liveRuns.length > 0 || finishedRuns.length > 0;
return (
- <Flex direction="column" gap="4" className="mx-auto max-w-3xl px-6 py-4">
+ <div className="@container mx-auto flex w-full max-w-3xl flex-col gap-4 px-6 py-4">
{!hasAnyRuns ? (
<Empty className="mx-auto max-w-md py-16">
<EmptyHeader>
@@ -107,7 +106,7 @@ export function RunsTab() {
</EmptyHeader>
</Empty>
) : (
- <Flex direction="column" gap="5">
+ <div className="flex flex-col gap-5">
{queuedRuns.length > 0 && (
<RunsSection
title="Queued"
@@ -135,9 +134,9 @@ export function RunsTab() {
showAll={finishedShowAll}
/>
)}
- </Flex>
+ </div>
)}
- </Flex>
+ </div>
);
}
@@ -181,16 +180,16 @@ function RunsSection({
showAll,
}: RunsSectionProps) {
return (
- <Flex direction="column" gap="2">
- <Flex direction="column" gap="0.5" className="cursor-default select-none">
- <Flex align="center" gap="2">
- <Text className="font-semibold text-[13px] text-gray-12">
+ <div className="flex flex-col gap-2">
+ <div className="flex cursor-default select-none flex-col gap-0.5">
+ <div className="flex items-center gap-2">
+ <span className="font-semibold text-[13px] text-gray-12">
{title}
- </Text>
+ </span>
{count > 0 && (
- <Text className="text-[12px] text-gray-10 tabular-nums">
+ <span className="text-[12px] text-gray-10 tabular-nums">
{count}
- </Text>
+ </span>
)}
{isLive && count > 0 && (
<span
@@ -198,41 +197,33 @@ function RunsSection({
aria-hidden
/>
)}
- </Flex>
+ </div>
{description && (
- <Text className="text-[12px] text-gray-11 leading-snug">
+ <span className="text-[12px] text-gray-11 leading-snug">
{description}
- </Text>
+ </span>
)}
- </Flex>
+ </div>
{runs.length === 0 && empty ? (
- <Flex
- align="center"
- gap="3"
- className="cursor-default select-none rounded-(--radius-2) border border-(--gray-5) border-dashed bg-(--gray-1) px-4 py-3.5"
- >
- <Flex
- align="center"
- justify="center"
- className="h-8 w-8 shrink-0 rounded-full bg-(--gray-3) ring-(--gray-5) ring-1 ring-inset"
- >
+ <div className="flex cursor-default select-none items-center gap-3 rounded-(--radius-2) border border-(--gray-5) border-dashed bg-(--gray-1) px-4 py-3.5">
+ <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-(--gray-3) ring-(--gray-5) ring-1 ring-inset">
<RobotIcon size={14} className="text-gray-10" />
- </Flex>
- <Flex direction="column" gap="0.5" className="min-w-0 flex-1">
- <Text className="font-medium text-[13px] text-gray-12">
+ </div>
+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">
+ <span className="font-medium text-[13px] text-gray-12">
{empty.title}
- </Text>
- <Text className="text-[12px] text-gray-10 leading-snug">
+ </span>
+ <span className="text-[12px] text-gray-10 leading-snug">
{empty.description}
- </Text>
- </Flex>
- </Flex>
+ </span>
+ </div>
+ </div>
) : (
- <Flex direction="column" gap="3">
+ <div className="flex flex-col gap-3">
{runs.map((report) => (
<AgentRunCard key={report.id} report={report} />
))}
- </Flex>
+ </div>
)}
{showAll && (
<button
@@ -245,6 +236,6 @@ function RunsSection({
: `Show all ${showAll.hiddenCount} more`}
</button>
)}
- </Flex>
+ </div>
);
}
diff --git a/products/desktop/packages/ui/src/features/inbox/components/SuggestedReviewersSection.tsx b/products/desktop/packages/ui/src/features/inbox/components/SuggestedReviewersSection.tsx
index 75e460435e48..415898edddb7 100644
--- a/products/desktop/packages/ui/src/features/inbox/components/SuggestedReviewersSection.tsx
+++ b/products/desktop/packages/ui/src/features/inbox/components/SuggestedReviewersSection.tsx
@@ -168,6 +168,7 @@ function SuggestedReviewersBody({
<RightColumnSection
Icon={User}
title="Reviewers"
+ collapsible
rightSlot={
<Flex align="center" gap="2">
{isPending && <Spinner size="1" />}
diff --git a/products/desktop/packages/ui/src/features/inbox/components/detail/ReportActivitySection.tsx b/products/desktop/packages/ui/src/features/inbox/components/detail/ReportActivitySection.tsx
index 641442048d7f..5b53435d2c21 100644
--- a/products/desktop/packages/ui/src/features/inbox/components/detail/ReportActivitySection.tsx
+++ b/products/desktop/packages/ui/src/features/inbox/components/detail/ReportActivitySection.tsx
@@ -33,6 +33,8 @@ export function ReportActivitySection({
<RightColumnSection
Icon={ClockCounterClockwiseIcon}
title="Activity"
+ collapsible
+ defaultCollapsed
rightSlot={
<Text className="cursor-default select-none text-[11px] text-gray-10 tabular-nums">
{artefacts.length} entr{artefacts.length === 1 ? "y" : "ies"}
diff --git a/products/desktop/packages/ui/src/features/inbox/components/detail/ReportChartCard.stories.tsx b/products/desktop/packages/ui/src/features/inbox/components/detail/ReportChartCard.stories.tsx
new file mode 100644
index 000000000000..d1399b5fb13d
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/inbox/components/detail/ReportChartCard.stories.tsx
@@ -0,0 +1,155 @@
+import type { Meta, StoryObj } from "@storybook/react";
+import { ReportChartCardView } from "./ReportChartCard";
+
+const meta: Meta<typeof ReportChartCardView> = {
+ title: "Inbox/ReportChartCard",
+ component: ReportChartCardView,
+ args: {
+ chartId: "story-chart",
+ title: "Daily query_wait_timeout exceptions",
+ caption: "Counts spike after the 2026-08-02 deploy.",
+ heightClass: "h-72",
+ openTarget: {
+ url: "https://us.posthog.com/project/2/sql?open_query=SELECT+1",
+ label: "Open in SQL editor",
+ },
+ onOpenExternal: () => {},
+ },
+ decorators: [
+ (Story) => (
+ <div style={{ maxWidth: 640 }}>
+ <Story />
+ </div>
+ ),
+ ],
+};
+export default meta;
+
+type Story = StoryObj<typeof ReportChartCardView>;
+
+const days = ["2026-08-01", "2026-08-02", "2026-08-03", "2026-08-04"];
+
+/** The dominant real-world shape: a HogQL day/count grid drawn as a line. */
+export const TimeSeriesLine: Story = {
+ args: {
+ state: {
+ kind: "data",
+ data: {
+ type: "series",
+ render: "line",
+ labels: days,
+ series: [{ key: "s0", label: "errors", data: [5, 42, 31, 12] }],
+ isTimeSeries: true,
+ interval: "day",
+ },
+ },
+ },
+};
+
+/** Multi-series pivot (date + breakdown + count) gets a legend. */
+export const TimeSeriesBarBreakdown: Story = {
+ args: {
+ state: {
+ kind: "data",
+ data: {
+ type: "series",
+ render: "bar",
+ labels: days,
+ series: [
+ { key: "s0", label: "Chrome", data: [5, 7, 6, 4] },
+ { key: "s1", label: "Safari", data: [2, 3, 1, 2] },
+ ],
+ isTimeSeries: true,
+ interval: "day",
+ },
+ },
+ },
+};
+
+/** Categorical first column keeps string labels on a band axis. */
+export const CategoricalBar: Story = {
+ args: {
+ state: {
+ kind: "data",
+ data: {
+ type: "series",
+ render: "bar",
+ labels: ["granted", "partial", "denied"],
+ series: [{ key: "s0", label: "count", data: [120, 14, 3] }],
+ isTimeSeries: false,
+ interval: "day",
+ },
+ },
+ },
+};
+
+/** A single numeric cell renders as a headline number, sized small. */
+export const SingleNumber: Story = {
+ args: {
+ heightClass: "max-h-36",
+ state: { kind: "data", data: { type: "number", value: 1284 } },
+ },
+};
+
+/** Non-graphical grids fall back to a scrolling table. */
+export const Table: Story = {
+ args: {
+ heightClass: "max-h-72",
+ state: {
+ kind: "data",
+ data: {
+ type: "table",
+ columns: ["path", "errors", "users"],
+ rows: [
+ ["/checkout", 42, 31],
+ ["/onboarding", 17, 15],
+ ["/settings", 3, 3],
+ ],
+ },
+ },
+ },
+};
+
+export const Loading: Story = {
+ args: { state: { kind: "loading" } },
+};
+
+/** Query failed: message plus the open-in-PostHog escape hatch. */
+export const QueryError: Story = {
+ args: {
+ heightClass: "max-h-72",
+ state: {
+ kind: "error",
+ message:
+ "Couldn't run the query behind this chart. Open it in PostHog to investigate.",
+ },
+ },
+};
+
+/** Query kinds the desktop app can't draw (funnels, saved insights, ...). */
+export const LinkOutFallback: Story = {
+ args: {
+ heightClass: "max-h-72",
+ state: { kind: "link-out" },
+ openTarget: {
+ url: "https://us.posthog.com/project/2/insights/abc123",
+ label: "Open insight",
+ },
+ },
+};
+
+/** A fallback whose query is too large to link (no dead button). */
+export const LinkOutWithoutTarget: Story = {
+ args: {
+ heightClass: "max-h-72",
+ state: { kind: "link-out" },
+ openTarget: null,
+ },
+};
+
+export const EmptyResult: Story = {
+ args: {
+ heightClass: "max-h-72",
+ state: { kind: "data", data: { type: "empty" } },
+ },
+};
diff --git a/products/desktop/packages/ui/src/features/inbox/components/detail/ReportChartCard.tsx b/products/desktop/packages/ui/src/features/inbox/components/detail/ReportChartCard.tsx
new file mode 100644
index 000000000000..493e530c199f
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/inbox/components/detail/ReportChartCard.tsx
@@ -0,0 +1,340 @@
+import { ArrowSquareOutIcon } from "@phosphor-icons/react";
+import {
+ planReportChart,
+ type ReportChartData,
+ type ReportChartOpenTarget,
+ reportChartHeightClass,
+ reportChartOpenTarget,
+} from "@posthog/core/inbox/reportCharts";
+import { cn } from "@posthog/quill";
+import {
+ BarChart,
+ LineChart,
+ type Series,
+ TimeSeriesBarChart,
+ TimeSeriesLineChart,
+ useChartTheme,
+} from "@posthog/quill-charts";
+import { getCloudUrlFromRegion } from "@posthog/shared";
+import type { SignalReportChart } from "@posthog/shared/types";
+import { useAuthStateValue } from "@posthog/ui/features/auth/store";
+import { useReportChartData } from "@posthog/ui/features/inbox/hooks/useReportChartData";
+import { Button } from "@posthog/ui/primitives/Button";
+import { openExternalUrl } from "@posthog/ui/shell/openExternal";
+import { useMemo } from "react";
+
+export type ReportChartCardState =
+ | { kind: "loading" }
+ | { kind: "error"; message: string }
+ | { kind: "data"; data: ReportChartData }
+ | { kind: "link-out" };
+
+export function reportChartAnchorId(chartId: string): string {
+ return `report-chart-${chartId}`;
+}
+
+function ChartSeriesBody({
+ data,
+}: {
+ data: Extract<ReportChartData, { type: "series" }>;
+}) {
+ const theme = useChartTheme();
+ const series: Series[] = data.series;
+ const config = {
+ legend: data.series.length > 1 ? { show: true } : undefined,
+ ...(data.isTimeSeries
+ ? { xAxis: { interval: data.interval, timezone: "UTC" } }
+ : {}),
+ };
+ if (data.isTimeSeries) {
+ return data.render === "bar" ? (
+ <TimeSeriesBarChart
+ series={series}
+ labels={data.labels}
+ theme={theme}
+ config={config}
+ />
+ ) : (
+ <TimeSeriesLineChart
+ series={series}
+ labels={data.labels}
+ theme={theme}
+ config={config}
+ />
+ );
+ }
+ return data.render === "bar" ? (
+ <BarChart
+ series={series}
+ labels={data.labels}
+ theme={theme}
+ config={config}
+ />
+ ) : (
+ <LineChart
+ series={series}
+ labels={data.labels}
+ theme={theme}
+ config={config}
+ />
+ );
+}
+
+function ChartTableBody({
+ data,
+}: {
+ data: Extract<ReportChartData, { type: "table" }>;
+}) {
+ return (
+ <div className="min-h-0 overflow-auto">
+ <table className="w-full border-collapse text-[12px]">
+ <thead>
+ <tr>
+ {data.columns.map((column) => (
+ <th
+ key={column}
+ className="sticky top-0 border-(--gray-4) border-b bg-(--color-panel-solid) px-2 py-1 text-left font-medium text-gray-11"
+ >
+ {column}
+ </th>
+ ))}
+ </tr>
+ </thead>
+ <tbody>
+ {data.rows.map((row, rowIndex) => (
+ // biome-ignore lint/suspicious/noArrayIndexKey: rows are static query results with no identity
+ <tr key={rowIndex}>
+ {row.map((cell, cellIndex) => (
+ <td
+ // biome-ignore lint/suspicious/noArrayIndexKey: cells are positional
+ key={cellIndex}
+ className="border-(--gray-3) border-b px-2 py-1 text-gray-11 tabular-nums"
+ >
+ {cell === null || cell === undefined ? "" : String(cell)}
+ </td>
+ ))}
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ );
+}
+
+function ChartMessageBody({
+ message,
+ openTarget,
+ onOpenExternal,
+}: {
+ message: string;
+ openTarget: ReportChartOpenTarget | null;
+ onOpenExternal: (url: string) => void;
+}) {
+ return (
+ <div className="flex flex-col items-center justify-center gap-2 py-6 text-center">
+ <span className="text-[12px] text-gray-10">{message}</span>
+ {openTarget && (
+ <Button
+ type="button"
+ variant="soft"
+ color="gray"
+ size="1"
+ onClick={() => onOpenExternal(openTarget.url)}
+ >
+ <ArrowSquareOutIcon size={12} />
+ {openTarget.label}
+ </Button>
+ )}
+ </div>
+ );
+}
+
+interface ReportChartCardViewProps {
+ chartId: string;
+ title: string;
+ caption?: string | null;
+ heightClass: string;
+ state: ReportChartCardState;
+ openTarget: ReportChartOpenTarget | null;
+ onOpenExternal?: (url: string) => void;
+}
+
+/** Pure card; the container resolves the query, plan, and open target. */
+export function ReportChartCardView({
+ chartId,
+ title,
+ caption,
+ heightClass,
+ state,
+ openTarget,
+ onOpenExternal = openExternalUrl,
+}: ReportChartCardViewProps) {
+ const body = (() => {
+ switch (state.kind) {
+ case "loading":
+ return (
+ <div className="h-full min-h-24 w-full animate-pulse rounded-(--radius-1) bg-(--gray-3)" />
+ );
+ case "error":
+ return (
+ <ChartMessageBody
+ message={state.message}
+ openTarget={openTarget}
+ onOpenExternal={onOpenExternal}
+ />
+ );
+ case "link-out":
+ return (
+ <ChartMessageBody
+ message="This chart can't be shown here yet."
+ openTarget={openTarget}
+ onOpenExternal={onOpenExternal}
+ />
+ );
+ case "data":
+ switch (state.data.type) {
+ case "series":
+ return <ChartSeriesBody data={state.data} />;
+ case "number":
+ return (
+ <div className="flex items-center justify-center py-4">
+ <span className="font-semibold text-3xl text-gray-12 tabular-nums">
+ {state.data.value.toLocaleString()}
+ </span>
+ </div>
+ );
+ case "table":
+ return <ChartTableBody data={state.data} />;
+ case "empty":
+ return (
+ <ChartMessageBody
+ message="The query behind this chart returned no data."
+ openTarget={openTarget}
+ onOpenExternal={onOpenExternal}
+ />
+ );
+ }
+ }
+ })();
+
+ const isFixedHeight = state.kind === "data" && state.data.type === "series";
+
+ return (
+ <figure
+ id={reportChartAnchorId(chartId)}
+ className="m-0 flex scroll-mt-4 flex-col gap-2 rounded-(--radius-2) border border-(--gray-4) bg-(--color-panel-solid) p-3"
+ data-testid="report-chart"
+ >
+ <div className="flex items-start justify-between gap-2">
+ <span className="min-w-0 break-words font-semibold text-[13px] text-gray-12">
+ {title}
+ </span>
+ {openTarget && (
+ <Button
+ type="button"
+ variant="ghost"
+ color="gray"
+ size="1"
+ aria-label={openTarget.label}
+ tooltipContent={openTarget.label}
+ className="shrink-0"
+ onClick={() => onOpenExternal(openTarget.url)}
+ >
+ <ArrowSquareOutIcon size={13} />
+ </Button>
+ )}
+ </div>
+ <div
+ className={cn(
+ "flex min-h-0 w-full flex-col",
+ heightClass,
+ !isFixedHeight && "overflow-y-auto",
+ )}
+ >
+ {body}
+ </div>
+ {caption && (
+ <figcaption className="m-0 text-[11px] text-gray-10">
+ {caption}
+ </figcaption>
+ )}
+ </figure>
+ );
+}
+
+function ReportChartCard({
+ reportId,
+ chart,
+}: {
+ reportId: string;
+ chart: SignalReportChart;
+}) {
+ const projectId = useAuthStateValue((state) => state.currentProjectId);
+ const cloudRegion = useAuthStateValue((state) => state.cloudRegion);
+
+ const plan = useMemo(() => planReportChart(chart.query), [chart.query]);
+ const query = useReportChartData(reportId, chart.chart_id, plan);
+
+ const openTarget = useMemo(() => {
+ if (!cloudRegion || !projectId) return null;
+ return reportChartOpenTarget(chart.query, {
+ cloudUrl: getCloudUrlFromRegion(cloudRegion),
+ projectId,
+ });
+ }, [chart.query, cloudRegion, projectId]);
+
+ if (plan.kind === "invalid") {
+ return null;
+ }
+
+ const state: ReportChartCardState =
+ plan.kind !== "run"
+ ? { kind: "link-out" }
+ : query.isPending
+ ? { kind: "loading" }
+ : query.isError
+ ? {
+ kind: "error",
+ message:
+ "Couldn't run the query behind this chart. Open it in PostHog to investigate.",
+ }
+ : { kind: "data", data: query.data };
+
+ return (
+ <ReportChartCardView
+ chartId={chart.chart_id}
+ title={chart.title}
+ caption={chart.caption}
+ heightClass={reportChartHeightClass(
+ chart.size,
+ state.kind === "data" ? state.data : null,
+ )}
+ state={state}
+ openTarget={openTarget}
+ />
+ );
+}
+
+/** All of a report's charts, rendered after the summary prose. */
+export function ReportChartsSection({
+ reportId,
+ charts,
+}: {
+ reportId: string;
+ charts: SignalReportChart[] | undefined;
+}) {
+ if (!charts?.length) {
+ return null;
+ }
+ return (
+ <div className="flex flex-col gap-3">
+ {charts.map((chart) => (
+ <ReportChartCard
+ key={chart.chart_id}
+ reportId={reportId}
+ chart={chart}
+ />
+ ))}
+ </div>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/inbox/components/utils/SignalReportSummaryMarkdown.tsx b/products/desktop/packages/ui/src/features/inbox/components/utils/SignalReportSummaryMarkdown.tsx
index 5de8eabe42b6..fefa8ace5dda 100644
--- a/products/desktop/packages/ui/src/features/inbox/components/utils/SignalReportSummaryMarkdown.tsx
+++ b/products/desktop/packages/ui/src/features/inbox/components/utils/SignalReportSummaryMarkdown.tsx
@@ -1,6 +1,16 @@
import { formatSignalReportSummaryMarkdown } from "@posthog/core/inbox/reportPresentation";
-import { MarkdownRenderer } from "@posthog/ui/features/editor/components/MarkdownRenderer";
-import { Box } from "@radix-ui/themes";
+import {
+ baseComponents,
+ MarkdownRenderer,
+} from "@posthog/ui/features/editor/components/MarkdownRenderer";
+import { reportChartAnchorId } from "@posthog/ui/features/inbox/components/detail/ReportChartCard";
+import { useMemo } from "react";
+import type { Components } from "react-markdown";
+
+const BaseAnchor = baseComponents.a as Extract<
+ Components["a"],
+ (...args: never[]) => unknown
+>;
interface SignalReportSummaryMarkdownProps {
content: string | null;
@@ -10,19 +20,39 @@ interface SignalReportSummaryMarkdownProps {
variant: "list" | "detail";
/** Render in italic to indicate the summary is still being written. */
pending?: boolean;
+ /**
+ * Ids of the charts rendered below this summary. `chart:` links to these
+ * become in-page jumps; every other chart reference degrades to plain text,
+ * matching the web inbox's no-renderer fallback.
+ */
+ chartIds?: readonly string[];
}
+// Matches the id charset the backend enforces on `chart_id` (report_charts.py).
+const CHART_REF = /^chart:[a-z0-9][a-z0-9_-]*$/;
+
+const listComponents: Partial<Components> = {
+ a: (props) => {
+ const { href, children } = props;
+ if (typeof href === "string" && CHART_REF.test(href)) {
+ return <span>{children}</span>;
+ }
+ return <BaseAnchor {...props} />;
+ },
+};
+
/**
* Renders signal report summary as GFM markdown (matches backend / agent output).
*
* MarkdownRenderer inherits font-size from this wrapper, so setting `text-[Npx]`
- * on the outer Box cascades to every paragraph / em / strong / code / link.
+ * on the outer div cascades to every paragraph / em / strong / code / link.
*/
export function SignalReportSummaryMarkdown({
content,
fallback,
variant,
pending,
+ chartIds,
}: SignalReportSummaryMarkdownProps) {
const rawContent = content?.trim() ? content : fallback;
const raw = formatSignalReportSummaryMarkdown(rawContent);
@@ -32,13 +62,49 @@ export function SignalReportSummaryMarkdown({
const pendingClass = pending ? "italic" : "";
+ const detailComponents = useMemo<Partial<Components>>(() => {
+ const renderedIds = new Set(chartIds ?? []);
+ return {
+ a: (props) => {
+ const { href, children } = props;
+ if (typeof href === "string" && CHART_REF.test(href)) {
+ const chartId = href.slice("chart:".length);
+ // A reference without a rendered card has nowhere to jump, so the
+ // label stays plain text instead of becoming a dead link.
+ if (!renderedIds.has(chartId)) {
+ return <span>{children}</span>;
+ }
+ const anchorId = reportChartAnchorId(chartId);
+ return (
+ <a
+ href={`#${anchorId}`}
+ className="markdown-link"
+ onClick={(event) => {
+ event.preventDefault();
+ document
+ .getElementById(anchorId)
+ ?.scrollIntoView({ behavior: "smooth", block: "center" });
+ }}
+ >
+ {children}
+ </a>
+ );
+ }
+ return <BaseAnchor {...props} />;
+ },
+ };
+ }, [chartIds]);
+
if (variant === "list") {
return (
- <Box
+ <div
className={`line-clamp-3 min-w-0 overflow-hidden text-pretty text-left text-[12px] text-gray-11 [&_.rt-Text]:mb-0! [&_a]:pointer-events-auto [&_li]:mb-0 [&_p]:mb-0! [&_ul]:mb-0! ${pendingClass}`}
>
- <MarkdownRenderer content={listMarkdown} />
- </Box>
+ <MarkdownRenderer
+ content={listMarkdown}
+ componentsOverride={listComponents}
+ />
+ </div>
);
}
@@ -47,10 +113,10 @@ export function SignalReportSummaryMarkdown({
// intrinsic – wider columns still get the prose, but narrower columns shrink
// the cap with the container.
return (
- <Box
+ <div
className={`min-w-0 max-w-[80ch] text-pretty break-words text-[13px] text-gray-11 [&_*]:leading-relaxed [&_.rt-Text]:mb-2 [&_a]:pointer-events-auto [&_li]:mb-1 [&_p:last-child]:mb-0 ${pendingClass}`}
>
- <MarkdownRenderer content={raw} />
- </Box>
+ <MarkdownRenderer content={raw} componentsOverride={detailComponents} />
+ </div>
);
}
diff --git a/products/desktop/packages/ui/src/features/inbox/hooks/useRefundReport.ts b/products/desktop/packages/ui/src/features/inbox/hooks/useRefundReport.ts
new file mode 100644
index 000000000000..b4f38dc523dc
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/inbox/hooks/useRefundReport.ts
@@ -0,0 +1,44 @@
+import { inboxReportKeys } from "@posthog/core/inbox/inboxQuery";
+import { SIGNALS_PR_REFUNDS_FLAG } from "@posthog/shared";
+import type {
+ SignalReport,
+ SignalReportRefundReason,
+} from "@posthog/shared/types";
+import { useAuthenticatedClient } from "@posthog/ui/features/auth/authClient";
+import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";
+import { computeRefundEligibility } from "@posthog/ui/features/inbox/utils/refundEligibility";
+import { toast } from "@posthog/ui/primitives/toast";
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+
+/**
+ * Refund-and-archive a report's PR, mirroring the web inbox. The button is
+ * offered only when the flag is on and the report has a billable PR that
+ * hasn't been refunded; the server enforces the same rules, so `canRefund`
+ * is a display gate.
+ */
+export function useRefundReport(report: SignalReport) {
+ const client = useAuthenticatedClient();
+ const queryClient = useQueryClient();
+ const flagEnabled = useFeatureFlag(SIGNALS_PR_REFUNDS_FLAG);
+
+ const { canRefund, disabledReason } = computeRefundEligibility(
+ report,
+ flagEnabled,
+ );
+
+ const mutation = useMutation({
+ mutationFn: (input: { reason: SignalReportRefundReason; note?: string }) =>
+ client.refundSignalReport(report.id, input),
+ onSuccess: () => {
+ toast.success("PR refunded. The report has been archived.");
+ queryClient.invalidateQueries({ queryKey: inboxReportKeys.all });
+ },
+ onError: (error) => {
+ toast.error(
+ error instanceof Error ? error.message : "Couldn't refund this PR.",
+ );
+ },
+ });
+
+ return { canRefund, disabledReason, mutation };
+}
diff --git a/products/desktop/packages/ui/src/features/inbox/hooks/useReportChartData.ts b/products/desktop/packages/ui/src/features/inbox/hooks/useReportChartData.ts
new file mode 100644
index 000000000000..50c224747a7f
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/inbox/hooks/useReportChartData.ts
@@ -0,0 +1,36 @@
+import { inboxReportKeys } from "@posthog/core/inbox/inboxQuery";
+import {
+ type ReportChartData,
+ type ReportChartPlan,
+ shapeReportChartData,
+} from "@posthog/core/inbox/reportCharts";
+import { useAuthenticatedQuery } from "@posthog/ui/hooks/useAuthenticatedQuery";
+import type { UseQueryResult } from "@tanstack/react-query";
+
+/**
+ * Executes a report chart's source query and shapes the response for
+ * rendering. Only fires for `run` plans; saved-insight and fallback cards
+ * never hit the network. Chart results are evidence snapshots, so they are
+ * cached long client-side and served cache-first by the backend
+ * (`refresh: "blocking"`).
+ */
+export function useReportChartData(
+ reportId: string,
+ chartId: string,
+ plan: ReportChartPlan,
+): UseQueryResult<ReportChartData> {
+ return useAuthenticatedQuery<ReportChartData>(
+ inboxReportKeys.chartData(reportId, chartId),
+ async (client) => {
+ if (plan.kind !== "run") return { type: "empty" };
+ const response = await client.runQuery(plan.source);
+ return shapeReportChartData(response, plan);
+ },
+ {
+ enabled: plan.kind === "run",
+ staleTime: 5 * 60 * 1000,
+ refetchOnWindowFocus: false,
+ retry: 1,
+ },
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/inbox/utils/refundEligibility.test.ts b/products/desktop/packages/ui/src/features/inbox/utils/refundEligibility.test.ts
new file mode 100644
index 000000000000..30e7869c8e8b
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/inbox/utils/refundEligibility.test.ts
@@ -0,0 +1,87 @@
+import type { SignalReport } from "@posthog/shared/types";
+import { describe, expect, it } from "vitest";
+import { computeRefundEligibility } from "./refundEligibility";
+
+function report(overrides: Partial<SignalReport> = {}): SignalReport {
+ return {
+ id: "report-1",
+ title: "Some report",
+ implementation_pr_url: "https://github.com/PostHog/posthog/pull/1",
+ refund: null,
+ billing_exempt_reason: null,
+ refund_ineligibility_reason: null,
+ ...overrides,
+ } as unknown as SignalReport;
+}
+
+describe("computeRefundEligibility", () => {
+ it.each([
+ ["flag off hides the button", { flagEnabled: false, overrides: {} }],
+ [
+ "no implementation PR hides the button",
+ { flagEnabled: true, overrides: { implementation_pr_url: null } },
+ ],
+ [
+ "an already-refunded report hides the button",
+ {
+ flagEnabled: true,
+ overrides: {
+ refund: { id: "r1", reason: "other" },
+ } as Partial<SignalReport>,
+ },
+ ],
+ [
+ "a billing-exempt report hides the button",
+ { flagEnabled: true, overrides: { billing_exempt_reason: "free" } },
+ ],
+ ])("%s", (_label, { flagEnabled, overrides }) => {
+ const result = computeRefundEligibility(report(overrides), flagEnabled);
+ expect(result.canRefund).toBe(false);
+ expect(result.disabledReason).toBeNull();
+ });
+
+ it("offers the button for a billable, unrefunded PR", () => {
+ const result = computeRefundEligibility(report(), true);
+ expect(result.canRefund).toBe(true);
+ expect(result.disabledReason).toBeNull();
+ });
+
+ it.each([
+ [
+ "out_of_period",
+ "This PR was billed in a previous billing period and can no longer be refunded.",
+ ],
+ ["no_billable_pr", "This PR isn't billable, so there's nothing to refund."],
+ ])(
+ "surfaces backend ineligibility copy for %s while keeping the button visible",
+ (reason, copy) => {
+ const result = computeRefundEligibility(
+ report({ refund_ineligibility_reason: reason }),
+ true,
+ );
+ expect(result.canRefund).toBe(true);
+ expect(result.disabledReason).toBe(copy);
+ },
+ );
+
+ it("falls back to generic copy for an unrecognized ineligibility reason", () => {
+ const result = computeRefundEligibility(
+ report({ refund_ineligibility_reason: "some_new_backend_reason" }),
+ true,
+ );
+ expect(result.canRefund).toBe(true);
+ expect(result.disabledReason).toBe("This PR can't be refunded right now.");
+ });
+
+ it("ignores an ineligibility reason when the button is hidden anyway", () => {
+ const result = computeRefundEligibility(
+ report({
+ implementation_pr_url: null,
+ refund_ineligibility_reason: "out_of_period",
+ }),
+ true,
+ );
+ expect(result.canRefund).toBe(false);
+ expect(result.disabledReason).toBeNull();
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/inbox/utils/refundEligibility.ts b/products/desktop/packages/ui/src/features/inbox/utils/refundEligibility.ts
new file mode 100644
index 000000000000..03dfa0a24423
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/inbox/utils/refundEligibility.ts
@@ -0,0 +1,41 @@
+import type { SignalReport } from "@posthog/shared/types";
+
+// Copy per backend `refund_ineligibility_reason`. `already_refunded` and
+// `billing_exempt` never reach the button (it is hidden for those), so only
+// the two visible-but-ineligible reasons map here.
+const REFUND_DISABLED_REASONS: Record<string, string> = {
+ out_of_period:
+ "This PR was billed in a previous billing period and can no longer be refunded.",
+ no_billable_pr: "This PR isn't billable, so there's nothing to refund.",
+};
+
+export interface RefundEligibility {
+ canRefund: boolean;
+ disabledReason: string | null;
+}
+
+/**
+ * Decide whether the refund control shows (`canRefund`) and, when it shows but
+ * the backend already knows it can't be refunded right now, the copy to display
+ * (`disabledReason`). The button is offered only when the flag is on and the
+ * report has a billable PR that hasn't been refunded; the server enforces the
+ * same rules, so this is a display gate.
+ */
+export function computeRefundEligibility(
+ report: SignalReport,
+ flagEnabled: boolean,
+): RefundEligibility {
+ const canRefund =
+ flagEnabled &&
+ !!report.implementation_pr_url &&
+ !report.refund &&
+ !report.billing_exempt_reason;
+
+ const disabledReason =
+ canRefund && report.refund_ineligibility_reason
+ ? (REFUND_DISABLED_REASONS[report.refund_ineligibility_reason] ??
+ "This PR can't be refunded right now.")
+ : null;
+
+ return { canRefund, disabledReason };
+}
diff --git a/products/desktop/packages/ui/src/features/pr-review/PrChecksSection.tsx b/products/desktop/packages/ui/src/features/pr-review/PrChecksSection.tsx
index 7c0764479573..b0f3af955227 100644
--- a/products/desktop/packages/ui/src/features/pr-review/PrChecksSection.tsx
+++ b/products/desktop/packages/ui/src/features/pr-review/PrChecksSection.tsx
@@ -1,7 +1,6 @@
import {
ArrowSquareOutIcon,
CheckCircleIcon,
- CheckIcon,
ChecksIcon,
CircleNotchIcon,
MinusCircleIcon,
@@ -11,7 +10,7 @@ import {
import type { PrCheck, PrCheckBucket } from "@posthog/core/git/router-schemas";
import { Spinner } from "@posthog/quill";
import { DetailSection } from "@posthog/ui/features/inbox/components/DetailSection";
-import { useMemo, useState } from "react";
+import { useMemo } from "react";
import { openExternalUrl } from "../../shell/openExternal";
import { usePrChecks } from "./usePrChecks";
@@ -36,24 +35,18 @@ const BUCKET_ORDER: Record<PrCheckBucket, number> = {
skipping: 4,
};
-/** Buckets that need attention — shown by default. */
-const DEFAULT_VISIBLE: PrCheckBucket[] = ["fail", "cancel", "pending"];
-
interface PrChecksSectionProps {
prUrl: string;
}
/**
- * CI status list for a PR. The header carries one checkbox per status bucket
- * (failed, running, successful, …) that filters the rows below; only the
- * attention-worthy buckets (failed, running) are shown by default.
+ * CI status list for a PR. The header summarizes each status bucket with its
+ * icon and count, like the web detail's CI checks card; the body lists every
+ * check, failures first.
*/
export function PrChecksSection({ prUrl }: PrChecksSectionProps) {
const checksQuery = usePrChecks(prUrl);
const checks = checksQuery.data;
- const [visibleBuckets, setVisibleBuckets] = useState<Set<PrCheckBucket>>(
- () => new Set(DEFAULT_VISIBLE),
- );
const sorted = useMemo(
() =>
@@ -100,83 +93,44 @@ export function PrChecksSection({ prUrl }: PrChecksSectionProps) {
if (checks.length === 0) return null;
- const toggleBucket = (bucket: PrCheckBucket) => {
- setVisibleBuckets((prev) => {
- const next = new Set(prev);
- if (next.has(bucket)) next.delete(bucket);
- else next.add(bucket);
- return next;
- });
- };
-
- const visible = sorted.filter((check) => visibleBuckets.has(check.bucket));
-
return (
<DetailSection
Icon={ChecksIcon}
title="Checks"
+ collapsible
+ // A fully green run folds away; failed, cancelled, or still-running
+ // checks keep the section open because they need attention.
+ defaultCollapsed={counts.fail + counts.cancel + counts.pending === 0}
rightSlot={
- <span className="flex items-center gap-1">
+ <span className="flex items-center gap-2.5">
{BUCKET_META.map(({ bucket, label, labelClass }) =>
counts[bucket] > 0 ? (
- <BucketFilterCheckbox
+ <span
key={bucket}
- checked={visibleBuckets.has(bucket)}
- onToggle={() => toggleBucket(bucket)}
- labelClass={labelClass}
- label={`${counts[bucket]} ${label}`}
- />
+ className={`inline-flex shrink-0 cursor-default select-none items-center gap-1 text-[11px] ${labelClass}`}
+ >
+ <CheckBucketIcon bucket={bucket} />
+ <span className="tabular-nums">
+ {counts[bucket]} {label}
+ </span>
+ </span>
) : null,
)}
</span>
}
>
- {visible.length > 0 && (
- <div className="overflow-hidden rounded-md border border-(--gray-5)">
- {visible.map((check, index) => (
- <CheckRow
- key={`${check.workflow ?? ""}/${check.name}/${index}`}
- check={check}
- />
- ))}
- </div>
- )}
+ <div className="overflow-hidden rounded-md border border-(--gray-5)">
+ {sorted.map((check, index) => (
+ <CheckRow
+ key={`${check.workflow ?? ""}/${check.name}/${index}`}
+ check={check}
+ />
+ ))}
+ </div>
</DetailSection>
);
}
-function BucketFilterCheckbox({
- checked,
- onToggle,
- label,
- labelClass,
-}: {
- checked: boolean;
- onToggle: () => void;
- label: string;
- labelClass: string;
-}) {
- return (
- <button
- type="button"
- aria-pressed={checked}
- onClick={onToggle}
- className="inline-flex shrink-0 cursor-pointer items-center gap-[5px] rounded border-0 bg-transparent px-[5px] py-[2px] text-[11px] hover:bg-gray-4"
- >
- <span
- className={`inline-flex h-[13px] w-[13px] items-center justify-center rounded-[3px] border ${
- checked
- ? "border-(--accent-9) bg-(--accent-9) text-white"
- : "border-(--gray-7)"
- }`}
- >
- {checked && <CheckIcon size={9} weight="bold" />}
- </span>
- <span className={`tabular-nums ${labelClass}`}>{label}</span>
- </button>
- );
-}
-
function CheckRow({ check }: { check: PrCheck }) {
return (
<button
diff --git a/products/desktop/packages/ui/src/features/pr-review/PrFilesChangedSection.tsx b/products/desktop/packages/ui/src/features/pr-review/PrFilesChangedSection.tsx
index 63e10d8b0493..04da35e3423d 100644
--- a/products/desktop/packages/ui/src/features/pr-review/PrFilesChangedSection.tsx
+++ b/products/desktop/packages/ui/src/features/pr-review/PrFilesChangedSection.tsx
@@ -1,36 +1,57 @@
-import { CheckIcon, GitDiffIcon } from "@phosphor-icons/react";
-import { Button, Spinner } from "@posthog/quill";
+import { CheckIcon, GitBranchIcon, GitDiffIcon } from "@phosphor-icons/react";
+import { Button, Spinner, ToggleGroup, ToggleGroupItem } from "@posthog/quill";
+import {
+ useDiffViewerStore,
+ type ViewMode,
+} from "@posthog/ui/features/code-editor/diffViewerStore";
import { PatchedFileDiff } from "@posthog/ui/features/code-review/components/PatchedFileDiff";
import { useDiffOptions } from "@posthog/ui/features/code-review/reviewShellParts";
import { usePrChangedFiles } from "@posthog/ui/features/git-interaction/useGitQueries";
import { DetailSection } from "@posthog/ui/features/inbox/components/DetailSection";
import { NestedButton } from "@posthog/ui/primitives/NestedButton";
-import { useMemo, useRef, useState } from "react";
+import { openExternalUrl } from "@posthog/ui/shell/openExternal";
+import { type ReactNode, useMemo, useRef, useState } from "react";
import {
fileViewedFingerprint,
isFileViewed,
usePrViewedFilesStore,
} from "./prViewedFilesStore";
+import { usePrInfo } from "./usePrInfo";
interface PrFilesChangedSectionProps {
prUrl: string;
+ /**
+ * Flat layout for a dedicated tab, like the web detail's Files changed
+ * page: a plain header row and the per-file diffs as siblings, instead of
+ * one card wrapping every diff.
+ */
+ bare?: boolean;
}
/**
* GitHub-style "Files changed" list for a PR: one collapsible diff per file,
- * all collapsed by default. An expanded file gets a footer row with the
- * "Viewed" toggle; marking a file viewed folds it back up.
+ * all expanded by default so the tab opens straight onto the changes. An
+ * expanded file gets a footer row with the "Viewed" toggle; marking a file
+ * viewed folds it back up.
*/
-export function PrFilesChangedSection({ prUrl }: PrFilesChangedSectionProps) {
+export function PrFilesChangedSection({
+ prUrl,
+ bare = false,
+}: PrFilesChangedSectionProps) {
const filesQuery = usePrChangedFiles(prUrl);
const diffOptions = useDiffOptions();
+ const viewMode = useDiffViewerStore((s) => s.viewMode);
+ const setViewMode = useDiffViewerStore((s) => s.setViewMode);
+ // The branch pill only renders in the tab layout; skip the fetch otherwise.
+ const prInfoQuery = usePrInfo(bare ? prUrl : null);
+ const headRefName = prInfoQuery.data?.headRefName ?? null;
const viewedByPr = usePrViewedFilesStore((s) => s.viewedByPr);
const markViewed = usePrViewedFilesStore((s) => s.markViewed);
const unmarkViewed = usePrViewedFilesStore((s) => s.unmarkViewed);
// Per-file collapse overrides on top of a section-wide baseline, so
// expand/collapse-all is one state flip instead of a map rebuild.
- const [baselineCollapsed, setBaselineCollapsed] = useState(true);
+ const [baselineCollapsed, setBaselineCollapsed] = useState(false);
const [collapseOverrides, setCollapseOverrides] = useState<
Map<string, boolean>
>(new Map());
@@ -50,33 +71,32 @@ export function PrFilesChangedSection({ prUrl }: PrFilesChangedSectionProps) {
[files, viewedByPr, prUrl],
);
- if (filesQuery.isLoading) {
- return (
+ const messageState = (body: ReactNode) =>
+ bare ? (
+ <div className="py-3 text-[12px] text-gray-10">{body}</div>
+ ) : (
<DetailSection Icon={GitDiffIcon} title="Files changed">
- <div className="flex items-center gap-2 py-3 text-[12px] text-gray-10">
- <Spinner />
- Loading changed files…
- </div>
+ <div className="py-3 text-[12px] text-gray-10">{body}</div>
</DetailSection>
);
+
+ if (filesQuery.isLoading) {
+ return messageState(
+ <span className="flex items-center gap-2">
+ <Spinner />
+ Loading changed files…
+ </span>,
+ );
}
if (filesQuery.isError || !files) {
- return (
- <DetailSection Icon={GitDiffIcon} title="Files changed">
- <div className="py-3 text-[12px] text-gray-10">
- Couldn't load the changed files for this pull request.
- </div>
- </DetailSection>
+ return messageState(
+ "Couldn't load the changed files for this pull request.",
);
}
if (files.length === 0) {
- return (
- <DetailSection Icon={GitDiffIcon} title="Files changed">
- <div className="py-3 text-[12px] text-gray-10">No changed files.</div>
- </DetailSection>
- );
+ return messageState("No changed files.");
}
const isCollapsed = (path: string) =>
@@ -88,95 +108,140 @@ export function PrFilesChangedSection({ prUrl }: PrFilesChangedSectionProps) {
setCollapseOverrides(new Map());
};
+ const headerControls = (
+ <span className="flex items-center gap-2">
+ <span className="cursor-default select-none text-[11px] text-gray-10 tabular-nums">
+ {viewedCount} / {files.length} viewed
+ </span>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => setAllCollapsed(allExpanded)}
+ >
+ {allExpanded ? "Collapse all" : "Expand all"}
+ </Button>
+ </span>
+ );
+
+ const fileList = (
+ <div className="flex flex-col gap-3">
+ {files.map((file) => {
+ const viewed = isFileViewed(viewedByPr, prUrl, file);
+ const collapsed = isCollapsed(file.path);
+ const setCollapsed = (next: boolean) =>
+ setCollapseOverrides((prev) => new Map(prev).set(file.path, next));
+ // Folding removes a diff that can be taller than the viewport,
+ // which would leave it staring at blank space below — scroll the
+ // folded file back into view. rAF runs after React commits the
+ // collapse but before the browser paints.
+ const collapseAndReveal = () => {
+ setCollapsed(true);
+ requestAnimationFrame(() => {
+ fileContainers.get(file.path)?.scrollIntoView({ block: "nearest" });
+ });
+ };
+ const handleViewedChange = (next: boolean) => {
+ if (next) {
+ markViewed(prUrl, file.path, fileViewedFingerprint(file));
+ // Fold the file away once it's read, like GitHub.
+ if (!collapsed) collapseAndReveal();
+ } else {
+ unmarkViewed(prUrl, file.path);
+ }
+ };
+ return (
+ <div
+ key={file.path}
+ ref={(el) => {
+ if (el) fileContainers.set(file.path, el);
+ else fileContainers.delete(file.path);
+ }}
+ className="overflow-hidden rounded-md border border-(--gray-5)"
+ >
+ <PatchedFileDiff
+ file={file}
+ taskId={prUrl}
+ options={diffOptions}
+ collapsed={collapsed}
+ onToggle={() => setCollapsed(!collapsed)}
+ externalUrl={`${prUrl}/files`}
+ prUrl={prUrl}
+ headerTrailing={
+ collapsed ? (
+ <ViewedToggle viewed={viewed} onChange={handleViewedChange} />
+ ) : undefined
+ }
+ />
+ {!collapsed && (
+ <div className="flex items-center justify-end gap-1 border-t border-t-(--gray-5) bg-(--gray-2) px-3 py-[4px]">
+ <button
+ type="button"
+ onClick={collapseAndReveal}
+ className="cursor-pointer rounded border-0 bg-transparent px-[6px] py-[2px] text-(--accent-9) text-[11px] hover:bg-gray-4"
+ >
+ Collapse
+ </button>
+ <ViewedToggle viewed={viewed} onChange={handleViewedChange} />
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ );
+
+ if (bare) {
+ return (
+ <div className="flex min-w-0 flex-col gap-3">
+ <div className="flex flex-wrap items-center justify-between gap-3">
+ <span className="flex min-w-0 items-center gap-2.5">
+ <span className="cursor-default select-none whitespace-nowrap font-semibold text-[13px] text-gray-12">
+ {files.length} file{files.length === 1 ? "" : "s"} changed
+ </span>
+ {headRefName && (
+ <button
+ type="button"
+ onClick={() => openExternalUrl(prUrl)}
+ className="inline-flex min-w-0 cursor-pointer items-center gap-1.5 rounded-full border border-(--accent-8) px-2.5 py-1 font-mono text-(--accent-11) text-[11px] hover:bg-(--accent-a3)"
+ title="Open the pull request on GitHub"
+ >
+ <GitBranchIcon size={11} className="shrink-0" />
+ <span className="truncate">{headRefName}</span>
+ </button>
+ )}
+ </span>
+ <span className="flex items-center gap-2">
+ <ToggleGroup
+ aria-label="Diff layout"
+ value={[viewMode]}
+ onValueChange={(next: string[]) => {
+ // Pressing the active item would otherwise clear the group —
+ // a layout is always on, so ignore the empty result.
+ const mode = next[0];
+ if (mode === "unified" || mode === "split") {
+ setViewMode(mode as ViewMode);
+ }
+ }}
+ >
+ <ToggleGroupItem value="unified">Unified</ToggleGroupItem>
+ <ToggleGroupItem value="split">Split</ToggleGroupItem>
+ </ToggleGroup>
+ {headerControls}
+ </span>
+ </div>
+ {fileList}
+ </div>
+ );
+ }
+
return (
<DetailSection
Icon={GitDiffIcon}
title={`Files changed (${files.length})`}
- rightSlot={
- <span className="flex items-center gap-2">
- <span className="cursor-default select-none text-[11px] text-gray-10 tabular-nums">
- {viewedCount} / {files.length} viewed
- </span>
- <Button
- type="button"
- variant="outline"
- size="sm"
- onClick={() => setAllCollapsed(allExpanded)}
- >
- {allExpanded ? "Collapse all" : "Expand all"}
- </Button>
- </span>
- }
+ rightSlot={headerControls}
>
- <div className="flex flex-col gap-3">
- {files.map((file) => {
- const viewed = isFileViewed(viewedByPr, prUrl, file);
- const collapsed = isCollapsed(file.path);
- const setCollapsed = (next: boolean) =>
- setCollapseOverrides((prev) => new Map(prev).set(file.path, next));
- // Folding removes a diff that can be taller than the viewport,
- // which would leave it staring at blank space below — scroll the
- // folded file back into view. rAF runs after React commits the
- // collapse but before the browser paints.
- const collapseAndReveal = () => {
- setCollapsed(true);
- requestAnimationFrame(() => {
- fileContainers
- .get(file.path)
- ?.scrollIntoView({ block: "nearest" });
- });
- };
- const handleViewedChange = (next: boolean) => {
- if (next) {
- markViewed(prUrl, file.path, fileViewedFingerprint(file));
- // Fold the file away once it's read, like GitHub.
- if (!collapsed) collapseAndReveal();
- } else {
- unmarkViewed(prUrl, file.path);
- }
- };
- return (
- <div
- key={file.path}
- ref={(el) => {
- if (el) fileContainers.set(file.path, el);
- else fileContainers.delete(file.path);
- }}
- className="overflow-hidden rounded-md border border-(--gray-5)"
- >
- <PatchedFileDiff
- file={file}
- taskId={prUrl}
- options={diffOptions}
- collapsed={collapsed}
- onToggle={() => setCollapsed(!collapsed)}
- externalUrl={`${prUrl}/files`}
- prUrl={prUrl}
- headerTrailing={
- collapsed ? (
- <ViewedToggle
- viewed={viewed}
- onChange={handleViewedChange}
- />
- ) : undefined
- }
- />
- {!collapsed && (
- <div className="flex items-center justify-end gap-1 border-t border-t-(--gray-5) bg-(--gray-2) px-3 py-[4px]">
- <button
- type="button"
- onClick={collapseAndReveal}
- className="cursor-pointer rounded border-0 bg-transparent px-[6px] py-[2px] text-(--accent-9) text-[11px] hover:bg-gray-4"
- >
- Collapse
- </button>
- <ViewedToggle viewed={viewed} onChange={handleViewedChange} />
- </div>
- )}
- </div>
- );
- })}
- </div>
+ {fileList}
</DetailSection>
);
}