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(self-driving): Show PR CI checks and comments on reports (#68636)

Michael Matloka5fc557a81a7b
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index cc591dca873a..05a273aa8e08 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6179,29 +6179,33 @@ snapshots:
scenes-app-inbox-cards--skeleton--light:
hash: v1.k794b7964.24c19ab5df1e4ccb843b1ad726752e3a98aeadaa08595e66cb4b41aff1a9e9a1.Y3z44tkU4jsAYUyXxfl72fTuZ0MKA6_S6TTNCKt5jSg
scenes-app-inbox-detail--pull-request--dark:
- hash: v1.k794b7964.afc834899dd290dd373afd5b9ef0f9481d5d5c895e92dcab5b656d278602035a.X5nW1dvAD5zn3RFeytk9dFvvjHj8FWVMlQW9h1XGMAo
+ hash: v1.k794b7964.588927d685f042c6ae2c344cae2c933d77ae414755fe233f96b5738379dafaec.Grly8apZQr_bHnB50GRU3zGS-26cL9_1_1yspWHS-1g
scenes-app-inbox-detail--pull-request--light:
- hash: v1.k794b7964.c2624da48e0b123f86b2cbceb9d11bc9935abf24d1aece6d2f1259f182439d4e.-fYiL53nvwVzWAf5fGKa9Ze0Qvze-VdG4uLVJ9gVUCU
+ hash: v1.k794b7964.81241ba93c915449049a4b7a031ee65786be1f86e02cbea1b48a4d03a2fcb565.PhkmcKNjTo65tyfb9uKFBd9pqXriYvXP28gY68MovUU
+ scenes-app-inbox-detail--pull-request-checks-passing--dark:
+ hash: v1.k794b7964.fa8c3efea43e09e4e8d64328f4c5da65fb33540f4d5fd38f5bf14dfa30fb2a5c.yl4EHtqzsp958-ddmQfX-UHbZjKCj-2FzLvemFdEDwU
+ scenes-app-inbox-detail--pull-request-checks-passing--light:
+ hash: v1.k794b7964.eeed41e7a22e885fd4594816445fa96e2da94c900007c5bda32c0dba2cb2fbc1.JzTydv37FrNThMEsks5YYUp6B7tHQAFtH15f7q6fqsw
scenes-app-inbox-detail--report--dark:
- hash: v1.k794b7964.1d75ec9c3bc54647bc0275b183ba1c3b0e4a50ae546c2796d2ccc8e7213c2eb7.s8cctju78p2KKN4rBtcwW-0B7rZvfH2S4awE_z4bJBk
+ hash: v1.k794b7964.5dbdb8db932b71d680cfe862320fdd7763f2e6fec0ba9619db3db30d3063e462.FVRwvM73SJe4aqe_th8_x5QTQB-S-ObnSWSZQWdcFQA
scenes-app-inbox-detail--report--light:
- hash: v1.k794b7964.a7ef412ce67a64dc50a6f39bcdcbae819ae469f834fe0c4774e8057e98f8da9e.SlB-3-uMV0Nx_dw1BEyd0myjI8K9SRjGi0xZbHwkB1I
+ hash: v1.k794b7964.1ff1da13acedacba704b9abc7e383dc9991e789986eb5fd97c6e5921d63d2bb1.kOa4M8V4szuzB71c6V8CzdtoE93zQjD4E2fUcjMFq5E
scenes-app-inbox-detail--report-minimal--dark:
- hash: v1.k794b7964.8cfc9e62bfd17e114ad92c87b90b0001f50e8bfc4eec52d651482d85b3f81e4a.1i2hZbDqM13hR1tjXuQmBHNUyyiM_MW52wiMhXO2Mdo
+ hash: v1.k794b7964.8305660b5d7b766742998c593180c174705e0d8e0992586057f4f9a076215f79.APH97qPdjLA8uJfWhFQ7Xod8FKAebIX-GjqbH-Zzw2s
scenes-app-inbox-detail--report-minimal--light:
- hash: v1.k794b7964.36bed308e7377b8b36a43b015d95d91cc4a1156f4c7dde7bd5d60bf9b29cdae4.kBXbfs9cEV7FwkIf_dNSHSW4UTLLDXA_ATLSA3LUe9c
+ hash: v1.k794b7964.cd3d39688b1af03a433d7505979961458153327143a04b9c380ab25b0df04c70.CeCxKJEfAPro-d45sz6jT2gCDCKoTHgjQF0D2thd-kI
scenes-app-inbox-detail--run-failed--dark:
- hash: v1.k794b7964.6694c0a4ba6adc4c39564eba480983fef70204296e62367e4d4967d0af76e544.SBnSmqIC6wqOb4FbDhPcxHOecFjXvW6mtg6ucQmh9hs
+ hash: v1.k794b7964.41531d56ba0552fc7dfa8210132986ba23509f44abe185787880d8f8ed68fd77.oMmQ-SVTUmTFOCFgABI4VTkeei1rqnJZEcC3cqfqLc8
scenes-app-inbox-detail--run-failed--light:
- hash: v1.k794b7964.ff57ae7224148abe673e732ec5ce814d52f360268ed923eaf02224678fa7e1d2.DcLYT3obN8dPPg66Lrp_IpWPzOgBZM8FywJyKN9Mu-Q
+ hash: v1.k794b7964.1a7ed1d5806de3a86538532382b12a0ab23fa4a748787b1174aeaa72b89aff9e.n4TxQhXzy5lAVmUVoRxkiL8jHfkIrGwNd93qcR0Sdfg
scenes-app-inbox-detail--run-in-progress--dark:
- hash: v1.k794b7964.6267c7d80c83db5568b966906fb475f1785a5faaaa6297ecb767b0de9a0d3424.vvJNzLnzEWkooT0ktwyR4vhZHYGeggrOnYa-OiF6BQ8
+ hash: v1.k794b7964.810aec6c132035ae39d60bf14e578eb0fc8e41335110aa96318f53b6fe4f4864.ivCuzW7RrvCzpmhy56m2c3nB2oybsL5Gylz95s7eNCc
scenes-app-inbox-detail--run-in-progress--light:
- hash: v1.k794b7964.20d906154218a9ac6d4352299e907146179d6a84562b3d3d0833543a7ad62c66.54IaeT75iihWgtxjXKoOTmBf3KwCZ5oeFQjTmUCQuko
+ hash: v1.k794b7964.755bda10e9ce9a4cde0d6d551c716d76515d27ffe5935a07482894ad0b8f91a2.KOqT19uKlE0Z-bIQRQx1fubDkzbYFH0-H0poog2V4r4
scenes-app-inbox-detail--run-ready--dark:
- hash: v1.k794b7964.66d1b7c3fc8d79cb7096bff1fbb60b89df30dbaa5910eb33e9575aafe988873c.vSnBncmDHUqdoqa_VuSEmfv4FjISlrTQl7uSh8AoPXI
+ hash: v1.k794b7964.87eec2401fe1055e531e24ba397051eff4accf9eb164806abcf2bbd757822938.2L9xMdpdtDgFbrV1X_y5feVL-MCgRXFC5F9pqWt-oKU
scenes-app-inbox-detail--run-ready--light:
- hash: v1.k794b7964.658259818177919f6c3fa1c95c07c2ee7b08ac76e3f2e16dd4fa66f1b918d4b0.vVrc6wtImibKFL3EexOIdaRoayuVV3M5eSsWzs9fJlU
+ hash: v1.k794b7964.60b0067bc9aace36c663aa7a2afb7bb716e1c8a0160c9d1e9600292e13a8fe95.stg-o3tY2gHi3SIk2eAIFL3-VrSMeLzzGEAlbg342Gw
scenes-app-inbox-pullrequestdiffview--default--dark:
hash: v1.k794b7964.564cd678d9da50089c918c63d37c816257091c6c9d7d2f957dc9c96f596d34dc.8ICzP4d5gRBF0h4CT87lZgk82tCHyXIOsszi6P3JQ-M
scenes-app-inbox-pullrequestdiffview--default--light:
diff --git a/frontend/src/scenes/inbox/components/detail/DetailSection.tsx b/frontend/src/scenes/inbox/components/detail/DetailSection.tsx
index 0335e018b9a4..4ed5c0d36608 100644
--- a/frontend/src/scenes/inbox/components/detail/DetailSection.tsx
+++ b/frontend/src/scenes/inbox/components/detail/DetailSection.tsx
@@ -1,12 +1,20 @@
import { ReactNode, useState } from 'react'
-import { IconChevronRight } from '@posthog/icons'
+import { IconCollapse, IconExpand } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
interface DetailSectionProps {
icon: ReactNode
title: string
/** Metadata rendered immediately after the title, before the divider (e.g. a branch tag, info icon). */
afterTitle?: ReactNode
+ /**
+ * Non-interactive summary rendered at the end of the header row, after the divider (e.g. a
+ * comment count). Part of the toggle when the section is collapsible — use `rightSlot` for
+ * anything with its own click behavior.
+ */
+ meta?: ReactNode
+ /** Interactive controls rendered outside the collapse toggle so they stay independently clickable. */
rightSlot?: ReactNode
children: ReactNode
/** When set, the header toggles the body open/closed. */
@@ -17,13 +25,16 @@ interface DetailSectionProps {
/**
* Content section with an icon + title header and a spanning divider, used throughout the report
- * detail (Summary, Files changed, Reviewers, Runs, Activity). Optionally collapsible — the header
- * becomes a toggle while `rightSlot` stays outside it so its own controls remain clickable.
+ * detail (Summary, Files changed, Reviewers, Runs, Activity). Optionally collapsible — the whole
+ * header row becomes a tertiary button toggle (expand/collapse icon at the row's end), while
+ * `rightSlot` stays outside it so its own controls remain clickable. Both variants render the
+ * same header row, so geometry is identical regardless of expandability.
*/
export function DetailSection({
icon,
title,
afterTitle,
+ meta,
rightSlot,
children,
collapsible = false,
@@ -32,35 +43,44 @@ export function DetailSection({
const [collapsed, setCollapsed] = useState(defaultCollapsed)
const open = !collapsible || !collapsed
- const heading = (
- <div className="flex items-center gap-2 min-w-0">
- <span className="flex shrink-0 items-center text-secondary [&_svg]:size-[0.9375rem]">{icon}</span>
- <span className="truncate font-semibold text-sm text-primary tracking-tight">{title}</span>
+ const headerRow = (
+ <div className="flex flex-1 items-center gap-3 min-w-0">
+ <div className="flex items-center gap-2 min-w-0">
+ <span className="flex shrink-0 items-center text-secondary [&_svg]:size-[0.9375rem]">{icon}</span>
+ <span className="truncate font-semibold text-sm text-primary tracking-tight">{title}</span>
+ {afterTitle && <div className="shrink-0">{afterTitle}</div>}
+ </div>
+ <div className="h-px min-w-4 flex-1 bg-border-light" />
+ {meta && <div className="shrink-0">{meta}</div>}
</div>
)
return (
<div className="flex flex-col gap-3">
<div className="flex items-center gap-3 min-w-0 select-none">
- <div className="flex items-center gap-2 min-w-0">
- {collapsible ? (
- <button
- type="button"
- aria-expanded={open}
- onClick={() => setCollapsed((c) => !c)}
- className="flex items-center gap-1.5 min-w-0 rounded text-left transition-colors hover:text-primary"
- >
- <IconChevronRight
- className={`size-3 shrink-0 text-tertiary transition-transform ${open ? 'rotate-90' : ''}`}
- />
- {heading}
- </button>
- ) : (
- heading
- )}
- {afterTitle && <div className="shrink-0">{afterTitle}</div>}
- </div>
- <div className="h-px min-w-4 flex-1 bg-border-light" />
+ {collapsible ? (
+ // The button keeps its natural small padding so the hover state wraps the row
+ // with a little air; `-ml-2` (= the small button's 0.5rem left padding) pulls the
+ // icon back onto the content column so it aligns with static section headers and
+ // the section bodies below.
+ <LemonButton
+ type="tertiary"
+ size="small"
+ fullWidth
+ onClick={() => setCollapsed((c) => !c)}
+ aria-expanded={open}
+ sideIcon={open ? <IconCollapse /> : <IconExpand />}
+ // `-my-px` trims the small button's extra height so its baseline matches the
+ // shorter static (non-button) headers.
+ className="min-w-0 flex-1 -ml-2 -my-px"
+ >
+ {headerRow}
+ </LemonButton>
+ ) : (
+ // Match the collapsible button's vertical padding so every section header sits on
+ // the same baseline whether or not it collapses.
+ <div className="flex flex-1 items-center min-w-0 py-1">{headerRow}</div>
+ )}
{rightSlot && <div className="shrink-0">{rightSlot}</div>}
</div>
{open && <div>{children}</div>}
diff --git a/frontend/src/scenes/inbox/components/detail/InboxDetail.stories.tsx b/frontend/src/scenes/inbox/components/detail/InboxDetail.stories.tsx
index 3917c93ab896..dabc91d9912d 100644
--- a/frontend/src/scenes/inbox/components/detail/InboxDetail.stories.tsx
+++ b/frontend/src/scenes/inbox/components/detail/InboxDetail.stories.tsx
@@ -21,6 +21,62 @@ import { AgentRunDetail } from './AgentRunDetail'
import { PullRequestDetail } from './PullRequestDetail'
import { ReportDetail } from './ReportDetail'
+const mixedPrChecks = {
+ checks: [
+ {
+ name: 'Frontend CI / TypeScript check',
+ status: 'completed',
+ conclusion: 'failure',
+ url: 'https://github.com/PostHog/posthog/actions/runs/12001/jobs/1',
+ },
+ {
+ name: 'Backend CI / Django tests – Core (persons-on-events off), Python 3.13, ClickHouse 26.3',
+ status: 'in_progress',
+ conclusion: null,
+ url: 'https://github.com/PostHog/posthog/actions/runs/12001/jobs/2',
+ },
+ {
+ name: 'Product analytics / Jest',
+ status: 'completed',
+ conclusion: 'success',
+ url: 'https://github.com/PostHog/posthog/actions/runs/12001/jobs/3',
+ },
+ {
+ name: 'Visual regression',
+ status: 'completed',
+ conclusion: 'cancelled',
+ url: 'https://github.com/PostHog/posthog/actions/runs/12001/jobs/4',
+ },
+ {
+ name: 'Dependency review',
+ status: 'completed',
+ conclusion: 'stale',
+ url: 'https://github.com/PostHog/posthog/actions/runs/12001/jobs/5',
+ },
+ {
+ name: 'Codecov / project',
+ status: 'completed',
+ conclusion: 'neutral',
+ url: 'https://app.codecov.io/gh/PostHog/posthog',
+ },
+ ],
+}
+
+const successfulPrChecks = {
+ checks: [
+ 'CI preflight',
+ 'Frontend CI / TypeScript check',
+ 'Frontend CI / Jest',
+ 'Backend CI / Django tests',
+ 'Visual regression',
+ ].map((name, index) => ({
+ name,
+ status: 'completed',
+ conclusion: 'success',
+ url: `https://github.com/PostHog/posthog/actions/runs/12002/jobs/${index + 1}`,
+ })),
+}
+
// Detail-body stories. Each detail component mounts the keyed `inboxReportDetailLogic`,
// which fetches artefacts / signals / tasks – mocked here. Polish the two-column detail
// layout (summary, evidence, runs, reviewers) against the desktop detail views.
@@ -36,6 +92,11 @@ const detailMocks = mswDecorator({
200,
{ report: null, signals: mockSignals(req.params.reportId as string, 4) },
],
+ '/api/projects/:id/signals/reports/:reportId/pr_checks/': (req) => [
+ 200,
+ req.params.reportId === pullRequestReports[1].id ? successfulPrChecks : mixedPrChecks,
+ ],
+ '/api/projects/:id/signals/reports/:reportId/pr_comments/': () => [200, { comments: [] }],
'/api/projects/:id/signals/reports/available_reviewers': () => [200, mockReviewers],
// Terminal run status so the inline run viewer replays its static log instead of opening SSE.
'/api/projects/:id/tasks/:taskId': (req) => [200, mockTask(req.params.taskId as string, 'completed')],
@@ -92,6 +153,14 @@ export const PullRequest: Story = {
),
}
+export const PullRequestChecksPassing: Story = {
+ render: () => (
+ <Frame>
+ <PullRequestDetail report={pullRequestReports[1]} />
+ </Frame>
+ ),
+}
+
export const RunInProgress: Story = {
render: () => (
<Frame>
diff --git a/frontend/src/scenes/inbox/components/detail/PrChecksSection.tsx b/frontend/src/scenes/inbox/components/detail/PrChecksSection.tsx
new file mode 100644
index 000000000000..5e70057507b1
--- /dev/null
+++ b/frontend/src/scenes/inbox/components/detail/PrChecksSection.tsx
@@ -0,0 +1,215 @@
+import { useValues } from 'kea'
+
+import {
+ IconCheckCircle,
+ IconCircleDashed,
+ IconClockRewind,
+ IconExternal,
+ IconSpinner,
+ IconWarning,
+ IconX,
+} from '@posthog/icons'
+import { LemonSkeleton, Link } from '@posthog/lemon-ui'
+
+import type { PullRequestCheckApi } from 'products/signals/frontend/generated/api.schemas'
+
+import { inboxReportDetailLogic } from '../../logics/inboxReportDetailLogic'
+import { SignalReport } from '../../types'
+import { DetailSection } from './DetailSection'
+
+type CheckVariant = 'failure' | 'cancelled' | 'pending' | 'stale' | 'success' | 'neutral'
+
+/** Collapse a GitHub check's (status, conclusion) pair into one of the buckets we render. */
+function resolveCheckVariant(check: PullRequestCheckApi): CheckVariant {
+ if (check.status !== 'completed') {
+ return 'pending'
+ }
+ switch (check.conclusion) {
+ case 'success':
+ return 'success'
+ case 'failure':
+ case 'timed_out':
+ case 'action_required':
+ case 'startup_failure':
+ return 'failure'
+ case 'cancelled':
+ return 'cancelled'
+ case 'stale':
+ return 'stale'
+ default:
+ // neutral / skipped / null-on-completed
+ return 'neutral'
+ }
+}
+
+const VARIANT_META: Record<
+ CheckVariant,
+ { icon: JSX.Element; label: string; iconClassName: string; summaryClassName: string }
+> = {
+ failure: {
+ icon: <IconWarning />,
+ label: 'Failed',
+ iconClassName: 'text-danger',
+ summaryClassName: 'text-danger',
+ },
+ cancelled: {
+ icon: <IconX />,
+ label: 'Cancelled',
+ iconClassName: 'text-muted',
+ summaryClassName: 'text-secondary',
+ },
+ pending: {
+ icon: <IconSpinner className="animate-spin motion-reduce:animate-none" />,
+ label: 'Running',
+ iconClassName: 'text-warning',
+ summaryClassName: 'text-warning',
+ },
+ stale: {
+ icon: <IconClockRewind />,
+ label: 'Stale',
+ iconClassName: 'text-muted',
+ summaryClassName: 'text-secondary',
+ },
+ success: {
+ icon: <IconCheckCircle />,
+ label: 'Successful',
+ iconClassName: 'text-success',
+ summaryClassName: 'text-success',
+ },
+ neutral: {
+ icon: <IconCircleDashed />,
+ label: 'Skipped',
+ iconClassName: 'text-muted',
+ summaryClassName: 'text-tertiary',
+ },
+}
+
+// Failed first, then in-flight, then the rest — the buckets worth a human's attention lead.
+const VARIANT_ORDER: CheckVariant[] = ['failure', 'pending', 'cancelled', 'stale', 'success', 'neutral']
+
+function CheckSummary({ variant, count }: { variant: CheckVariant; count: number }): JSX.Element | null {
+ if (count === 0) {
+ return null
+ }
+
+ const meta = VARIANT_META[variant]
+ return (
+ <span className={`inline-flex items-center gap-1 whitespace-nowrap ${meta.summaryClassName}`}>
+ <span className={`flex items-center [&_svg]:size-3 ${meta.iconClassName}`}>{meta.icon}</span>
+ <span className="font-medium tabular-nums">{count}</span>
+ <span>{meta.label.toLowerCase()}</span>
+ </span>
+ )
+}
+
+/**
+ * "CI checks" section for a report's implementation PR: the GitHub Actions check runs and legacy
+ * commit statuses of the PR's head commit, polled every 15s by `inboxReportDetailLogic` while the
+ * detail is open. Read-only — each row links out to the check on GitHub.
+ */
+export function PrChecksSection({ report }: { report: SignalReport }): JSX.Element | null {
+ const { prChecks, prChecksLoading, prChecksError } = useValues(
+ inboxReportDetailLogic({ reportId: report.id, report })
+ )
+
+ // Never loaded yet: show a skeleton. Loaded-but-empty: nothing to show, so drop the section.
+ if (prChecks === null) {
+ if (!prChecksLoading && !prChecksError) {
+ return null
+ }
+ } else if (prChecks.length === 0 && !prChecksError) {
+ return null
+ }
+
+ // Resolve each check's variant once, then sort/count off it — failed first, then in-flight, then
+ // the rest, so the buckets worth a human's attention lead.
+ const sorted = (prChecks ?? [])
+ .map((check) => ({ check, variant: resolveCheckVariant(check) }))
+ .sort((a, b) => VARIANT_ORDER.indexOf(a.variant) - VARIANT_ORDER.indexOf(b.variant))
+ const counts = sorted.reduce<Record<CheckVariant, number>>(
+ (result, { variant }) => {
+ result[variant] += 1
+ return result
+ },
+ { failure: 0, cancelled: 0, pending: 0, stale: 0, success: 0, neutral: 0 }
+ )
+ const hasChecksNeedingAttention =
+ counts.failure > 0 || counts.cancelled > 0 || counts.pending > 0 || counts.stale > 0
+
+ return (
+ <DetailSection
+ // `DetailSection` reads `defaultCollapsed` only on mount. This section mounts while
+ // `prChecks` is still null (skeleton), when the "all green → collapse" default computes to
+ // false, so remount once the checks resolve to let the settled default take effect.
+ key={prChecks === null ? 'checks-loading' : 'checks-loaded'}
+ icon={<IconCheckCircle />}
+ title="CI checks"
+ collapsible
+ defaultCollapsed={sorted.length > 0 && !hasChecksNeedingAttention}
+ meta={
+ sorted.length > 0 ? (
+ <span className="flex items-center justify-end gap-x-2.5 gap-y-1 flex-wrap text-[0.6875rem]">
+ {VARIANT_ORDER.map((variant) => (
+ <CheckSummary key={variant} variant={variant} count={counts[variant]} />
+ ))}
+ </span>
+ ) : undefined
+ }
+ >
+ {prChecksError ? (
+ <div className="rounded border border-danger bg-danger-highlight px-3 py-2.5 text-sm text-danger">
+ {prChecksError}
+ </div>
+ ) : prChecks === null ? (
+ <div className="overflow-hidden rounded border border-primary bg-surface-primary">
+ <LemonSkeleton className="h-10 w-full rounded-none" />
+ <LemonSkeleton className="h-10 w-full rounded-none border-t border-primary" />
+ <LemonSkeleton className="h-10 w-full rounded-none border-t border-primary" />
+ </div>
+ ) : (
+ <ul className="m-0 max-h-96 overflow-y-auto rounded border border-primary bg-surface-primary p-0 list-none divide-y divide-border">
+ {sorted.map(({ check, variant }, i) => {
+ const meta = VARIANT_META[variant]
+ const row = (
+ <>
+ <span
+ className={`flex shrink-0 items-center [&_svg]:size-[1.125rem] ${meta.iconClassName}`}
+ aria-hidden
+ >
+ {meta.icon}
+ </span>
+ <span
+ className="min-w-0 flex-1 truncate text-sm font-medium text-primary"
+ title={check.name}
+ >
+ {check.name}
+ </span>
+ <span className="shrink-0 text-xs text-tertiary transition-colors group-hover:text-secondary">
+ {meta.label}
+ </span>
+ {check.url && (
+ <IconExternal className="size-3.5 shrink-0 text-tertiary opacity-60 transition-opacity group-hover:opacity-100" />
+ )}
+ </>
+ )
+ return (
+ <li key={`${check.name}-${i}`}>
+ {check.url ? (
+ <Link
+ to={check.url}
+ target="_blank"
+ className="group flex min-w-0 items-center gap-2.5 px-3 py-2.5 text-primary no-underline transition-colors hover:bg-fill-highlight-50 hover:text-primary focus-visible:bg-fill-highlight-50"
+ >
+ {row}
+ </Link>
+ ) : (
+ <span className="group flex min-w-0 items-center gap-2.5 px-3 py-2.5">{row}</span>
+ )}
+ </li>
+ )
+ })}
+ </ul>
+ )}
+ </DetailSection>
+ )
+}
diff --git a/frontend/src/scenes/inbox/components/detail/PrCommentsSection.tsx b/frontend/src/scenes/inbox/components/detail/PrCommentsSection.tsx
new file mode 100644
index 000000000000..d2400ea74afe
--- /dev/null
+++ b/frontend/src/scenes/inbox/components/detail/PrCommentsSection.tsx
@@ -0,0 +1,107 @@
+import { useValues } from 'kea'
+
+import { IconComment, IconExternal } from '@posthog/icons'
+import { LemonSkeleton, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'
+
+import { TZLabel } from 'lib/components/TZLabel'
+import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'
+
+import type { PullRequestCommentApi } from 'products/signals/frontend/generated/api.schemas'
+
+import { inboxReportDetailLogic } from '../../logics/inboxReportDetailLogic'
+import { SignalReport } from '../../types'
+import { DetailSection } from './DetailSection'
+
+/** A single PR comment row: avatar, author, relative time, optional file path, then the markdown body. */
+function CommentRow({ comment }: { comment: PullRequestCommentApi }): JSX.Element {
+ return (
+ <li className="flex gap-2.5 min-w-0">
+ {comment.author_avatar_url ? (
+ <img
+ src={comment.author_avatar_url}
+ alt={comment.author ?? 'author'}
+ className="size-6 shrink-0 rounded-full bg-fill-highlight-50"
+ loading="lazy"
+ />
+ ) : (
+ <span className="size-6 shrink-0 rounded-full bg-fill-highlight-100" aria-hidden />
+ )}
+ <div className="flex flex-col gap-1 min-w-0 flex-1">
+ <div className="flex items-center gap-2 flex-wrap text-xs text-tertiary min-w-0">
+ <span className="font-semibold text-secondary">{comment.author ?? 'Unknown'}</span>
+ {comment.created_at && <TZLabel time={comment.created_at} />}
+ {comment.comment_type === 'review' && comment.path && (
+ <Tooltip title={comment.path}>
+ <LemonTag type="muted" className="font-mono max-w-[16rem]">
+ <span className="truncate">{comment.path}</span>
+ </LemonTag>
+ </Tooltip>
+ )}
+ {comment.url && (
+ <Link to={comment.url} target="_blank" className="inline-flex items-center text-tertiary">
+ <IconExternal className="size-3.5" />
+ </Link>
+ )}
+ </div>
+ {comment.body ? (
+ <LemonMarkdown className="text-sm text-secondary leading-relaxed break-words" disableImages>
+ {comment.body}
+ </LemonMarkdown>
+ ) : (
+ <p className="m-0 text-sm text-tertiary italic">No content.</p>
+ )}
+ </div>
+ </li>
+ )
+}
+
+/**
+ * "Comments" section for a report's implementation PR: the PR's conversation comments and inline
+ * review comments merged chronologically. Read-only mirror of the GitHub thread — each comment
+ * links out to GitHub. Collapsed by default so it doesn't crowd the overview.
+ */
+export function PrCommentsSection({ report }: { report: SignalReport }): JSX.Element | null {
+ const { prComments, prCommentsLoading, prCommentsError } = useValues(
+ inboxReportDetailLogic({ reportId: report.id, report })
+ )
+
+ // Never loaded yet: show a skeleton. Loaded-but-empty: nothing to show, so drop the section.
+ if (prComments === null) {
+ if (!prCommentsLoading && !prCommentsError) {
+ return null
+ }
+ } else if (prComments.length === 0 && !prCommentsError) {
+ return null
+ }
+
+ return (
+ <DetailSection
+ icon={<IconComment />}
+ title="Comments"
+ collapsible
+ defaultCollapsed
+ meta={
+ prComments && prComments.length > 0 ? (
+ <span className="text-[0.6875rem] text-tertiary tabular-nums">
+ {prComments.length} comment{prComments.length === 1 ? '' : 's'}
+ </span>
+ ) : undefined
+ }
+ >
+ {prCommentsError ? (
+ <p className="m-0 py-2 text-sm text-danger">{prCommentsError}</p>
+ ) : prComments === null ? (
+ <div className="flex flex-col gap-3">
+ <LemonSkeleton className="h-10 w-full" />
+ <LemonSkeleton className="h-10 w-4/5" />
+ </div>
+ ) : (
+ <ul className="flex flex-col gap-4 m-0 p-0 list-none">
+ {prComments.map((comment) => (
+ <CommentRow key={comment.id} comment={comment} />
+ ))}
+ </ul>
+ )}
+ </DetailSection>
+ )
+}
diff --git a/frontend/src/scenes/inbox/components/detail/PullRequestDiffPanel.tsx b/frontend/src/scenes/inbox/components/detail/PullRequestDiffPanel.tsx
index 9d04dd77ade6..e13c922b2961 100644
--- a/frontend/src/scenes/inbox/components/detail/PullRequestDiffPanel.tsx
+++ b/frontend/src/scenes/inbox/components/detail/PullRequestDiffPanel.tsx
@@ -14,6 +14,70 @@ const DIFF_STYLE_OPTIONS = [
{ value: 'split' as const, label: 'Split' },
]
+/**
+ * The diff's +/- line counts, shown in the "Files changed" tab label beside the branch so the size of
+ * the change reads at a glance even while the tab is collapsed. Renders nothing until the diff loads
+ * (or if it's empty). Reads the same `reportDiff` the panel body does — no extra fetch.
+ */
+export function PullRequestDiffStat({
+ report,
+ commit,
+}: {
+ report: SignalReport
+ commit: CommitContent
+}): JSX.Element | null {
+ const { reportDiff, reportDiffError } = useValues(inboxReportDetailLogic({ reportId: report.id, report }))
+ const summary = useMemo(
+ () => (reportDiff ? summarizeDiff(reportDiff.diff, commit.commit_sha) : null),
+ [reportDiff, commit.commit_sha]
+ )
+ // Reserve the stat's space while the patch is still loading, so it doesn't pop into the tab label —
+ // but on a load error there's no stat to wait for, so drop it (the panel body shows the error).
+ if (!reportDiff) {
+ return reportDiffError ? null : <PullRequestDiffStatSkeleton />
+ }
+ if (!summary || (summary.additions === 0 && summary.deletions === 0)) {
+ return null
+ }
+ return (
+ <span className="flex shrink-0 items-center gap-1.5 font-mono text-xs tabular-nums">
+ {summary.deletions > 0 && <span className="text-danger">-{summary.deletions}</span>}
+ {summary.additions > 0 && <span className="text-success">+{summary.additions}</span>}
+ </span>
+ )
+}
+
+/** Mini placeholders for the "Files changed" tab label, shown from the moment we know the report has a
+ * PR until the commit artefact (branch) and its diff (size) load — so the tab bar appears immediately
+ * instead of a beat later. */
+export function PullRequestDiffStatSkeleton(): JSX.Element {
+ return <LemonSkeleton className="h-3.5 w-9 rounded" />
+}
+
+export function PullRequestBranchTagSkeleton(): JSX.Element {
+ return <LemonSkeleton className="h-[1.375rem] w-24 rounded" />
+}
+
+/**
+ * "Files changed" tab body shown before the commit artefact resolves: a diff skeleton while the branch
+ * is still loading, or a fallback to GitHub if the artefacts finished loading without a diffable commit.
+ */
+export function PullRequestDiffPending({ artefactsLoaded }: { artefactsLoaded: boolean }): JSX.Element {
+ if (artefactsLoaded) {
+ return (
+ <p className="m-0 py-4 text-sm text-tertiary">
+ The diff isn't available here. Open the pull request on GitHub to review the changes.
+ </p>
+ )
+ }
+ return (
+ <div className="flex flex-col gap-2">
+ <LemonSkeleton className="h-8 w-full" />
+ <LemonSkeleton className="h-24 w-full" />
+ </div>
+ )
+}
+
/**
* The report's branch as a git-branch tag. Rendered in the "Files changed" tab label (so the tab
* signals there's code behind it, GitHub-style) — inside the LemonTabs active tab it picks up the
@@ -38,7 +102,8 @@ export function PullRequestBranchTag({ commit }: { commit: CommitContent }): JSX
* state, tracking the branch tip as the work moves.
*/
export function PullRequestDiffPanel({ report, commit }: { report: SignalReport; commit: CommitContent }): JSX.Element {
- const { reportDiff, reportDiffError } = useValues(inboxReportDetailLogic({ reportId: report.id, report }))
+ const logicProps = useMemo(() => ({ reportId: report.id, report }), [report])
+ const { reportDiff, reportDiffError } = useValues(inboxReportDetailLogic(logicProps))
const [diffStyle, setDiffStyle] = useState<'unified' | 'split'>('unified')
const diffSummary = useMemo(
() => (reportDiff ? summarizeDiff(reportDiff.diff, commit.commit_sha) : null),
@@ -60,12 +125,14 @@ export function PullRequestDiffPanel({ report, commit }: { report: SignalReport;
{reportDiffError ? (
<p className="m-0 py-4 text-sm text-danger">{reportDiffError}</p>
) : reportDiff ? (
- <PullRequestDiffView
- diff={reportDiff.diff}
- truncated={reportDiff.truncated}
- cacheKey={commit.commit_sha}
- diffStyle={diffStyle}
- />
+ <>
+ <PullRequestDiffView
+ diff={reportDiff.diff}
+ truncated={reportDiff.truncated}
+ cacheKey={commit.commit_sha}
+ diffStyle={diffStyle}
+ />
+ </>
) : (
<div className="flex flex-col gap-2">
<LemonSkeleton className="h-8 w-full" />
@@ -88,14 +155,9 @@ function DiffToolbarSummary({
const fileLabel = diffSummary.fileCount === 1 ? '1 file changed' : `${diffSummary.fileCount} files changed`
return (
+ // The +/- line stat lives in the "Files changed" tab label now, so the toolbar carries the file count.
<div className="flex min-w-0 items-center gap-2 text-sm">
<span className="truncate text-secondary">{fileLabel}</span>
- {(diffSummary.additions > 0 || diffSummary.deletions > 0) && (
- <span className="flex shrink-0 items-center gap-2 font-mono text-xs tabular-nums">
- {diffSummary.deletions > 0 && <span className="text-danger">-{diffSummary.deletions}</span>}
- {diffSummary.additions > 0 && <span className="text-success">+{diffSummary.additions}</span>}
- </span>
- )}
</div>
)
}
diff --git a/frontend/src/scenes/inbox/components/detail/PullRequestDiffView.tsx b/frontend/src/scenes/inbox/components/detail/PullRequestDiffView.tsx
index 655fad4beaf1..beafaefa9395 100644
--- a/frontend/src/scenes/inbox/components/detail/PullRequestDiffView.tsx
+++ b/frontend/src/scenes/inbox/components/detail/PullRequestDiffView.tsx
@@ -1,7 +1,7 @@
import { type ChangeTypes, type FileDiffMetadata, type FileDiffOptions, parsePatchFiles } from '@pierre/diffs'
import { FileDiff } from '@pierre/diffs/react'
import { useValues } from 'kea'
-import { ReactNode, useMemo } from 'react'
+import { ReactNode, useEffect, useMemo, useRef, useState } from 'react'
import { IconArrowRight, IconMinus, IconPencil, IconPlus } from '@posthog/icons'
import { Tooltip } from '@posthog/lemon-ui'
@@ -22,12 +22,107 @@ const CHANGE_META: Record<ChangeTypes, { label: string; icon: ReactNode; classNa
'rename-changed': { label: 'Renamed', icon: <IconArrowRight />, className: 'text-secondary' },
}
+// Rough per-row / header heights (px) of Pierre's rendered diff, used only to size the loading
+// placeholder so the card doesn't collapse to a bare header while highlighting runs.
+const DIFF_ROW_HEIGHT = 20
+const DIFF_HEADER_HEIGHT = 37
+
export interface DiffSummary {
fileCount: number
additions: number
deletions: number
}
+/** Estimate how many rows a file's diff renders, to size its loading placeholder. Capped so a huge
+ * file doesn't reserve a screen-height of skeleton. */
+function estimateDiffRows(file: FileDiffMetadata): number {
+ let rows = 0
+ for (const hunk of file.hunks) {
+ // Added + deleted changed lines, plus a little context around each hunk.
+ rows += hunk.additionLines + hunk.deletionLines + 3
+ }
+ return Math.max(3, Math.min(rows, 18))
+}
+
+const SKELETON_LINE_WIDTHS = ['w-3/4', 'w-1/2', 'w-5/6', 'w-2/3', 'w-4/5', 'w-1/3', 'w-3/5', 'w-11/12']
+
+/** Code-shaped placeholder (header bar + gutter + line rows) shown over a file's card until Pierre
+ * finishes highlighting its body — otherwise the body is empty and files read as stacked header rules. */
+function DiffFileCardSkeleton({ rows }: { rows: number }): JSX.Element {
+ return (
+ <div className="animate-pulse" aria-hidden>
+ <div
+ className="flex items-center gap-2 border-b border-primary px-3"
+ style={{ height: DIFF_HEADER_HEIGHT }}
+ >
+ <div className="size-3.5 shrink-0 rounded bg-fill-highlight-100" />
+ <div className="h-2.5 w-40 rounded bg-fill-highlight-100" />
+ </div>
+ <div className="flex flex-col py-1">
+ {Array.from({ length: rows }).map((_, i) => (
+ <div key={i} className="flex items-center gap-3 px-3" style={{ height: DIFF_ROW_HEIGHT }}>
+ <div className="h-2.5 w-6 shrink-0 rounded bg-fill-highlight-50" />
+ <div
+ className={`h-2.5 rounded bg-fill-highlight-50 ${SKELETON_LINE_WIDTHS[i % SKELETON_LINE_WIDTHS.length]}`}
+ />
+ </div>
+ ))}
+ </div>
+ </div>
+ )
+}
+
+/**
+ * Card chrome around one file's `FileDiff`. `@pierre/diffs` highlights the body asynchronously (Shiki),
+ * so on first paint the body is empty and the file is just its header. This reserves an estimated height
+ * and overlays a skeleton until the real body renders — detected by the wrapper growing past its header
+ * (with a timeout fallback for degenerate zero-line files that never grow).
+ */
+function DiffFileCard({ file, children }: { file: FileDiffMetadata; children: ReactNode }): JSX.Element {
+ const [rendered, setRendered] = useState(false)
+ const bodyRef = useRef<HTMLDivElement>(null)
+ const rows = useMemo(() => estimateDiffRows(file), [file])
+
+ useEffect(() => {
+ const el = bodyRef.current
+ if (!el) {
+ return
+ }
+ let done = false
+ const finish = (): void => {
+ if (!done) {
+ done = true
+ setRendered(true)
+ }
+ }
+ const observer = new ResizeObserver(() => {
+ if (el.offsetHeight > DIFF_HEADER_HEIGHT + DIFF_ROW_HEIGHT) {
+ finish()
+ }
+ })
+ observer.observe(el)
+ const timer = setTimeout(finish, 2500)
+ return () => {
+ observer.disconnect()
+ clearTimeout(timer)
+ }
+ }, [])
+
+ return (
+ <div
+ className="relative overflow-hidden rounded-lg border border-primary bg-surface-primary"
+ style={rendered ? undefined : { minHeight: DIFF_HEADER_HEIGHT + rows * DIFF_ROW_HEIGHT }}
+ >
+ <div ref={bodyRef}>{children}</div>
+ {!rendered && (
+ <div className="absolute inset-0 bg-surface-primary">
+ <DiffFileCardSkeleton rows={rows} />
+ </div>
+ )}
+ </div>
+ )
+}
+
/** Aggregate file/line counts from a unified diff patch — shared by the diff toolbar and file headers. */
export function summarizeDiff(diff: string, cacheKey?: string): DiffSummary | null {
if (!diff.trim()) {
@@ -112,7 +207,7 @@ export function PullRequestDiffView({
}
}, [diff, cacheKey])
- const options = useMemo<FileDiffOptions<undefined>>(
+ const options = useMemo<FileDiffOptions<never>>(
() => ({
theme: DIFF_THEME,
themeType: isDarkModeOn ? 'dark' : 'light',
@@ -134,19 +229,16 @@ export function PullRequestDiffView({
return (
<div className="flex flex-col gap-3">
{files.map((file) => (
- // Card chrome around each file so the diff sits in PostHog's visual language (bordered,
- // rounded surface); @pierre/diffs renders the syntax-highlighted body inside.
- <div
- key={`${file.name}-${file.cacheKey ?? file.newObjectId ?? ''}`}
- className="overflow-hidden rounded-lg border border-primary bg-surface-primary"
- >
+ // Card chrome (bordered, rounded surface) so the diff sits in PostHog's visual language;
+ // @pierre/diffs renders the syntax-highlighted body inside, with a skeleton until it does.
+ <DiffFileCard key={`${file.name}-${file.cacheKey ?? file.newObjectId ?? ''}`} file={file}>
<FileDiff
fileDiff={file}
options={options}
renderCustomHeader={(fileDiff) => <FileDiffHeader file={fileDiff} />}
disableWorkerPool
/>
- </div>
+ </DiffFileCard>
))}
{truncated ? (
<p className="m-0 text-xs text-tertiary italic">
diff --git a/frontend/src/scenes/inbox/components/detail/ReportDetail.tsx b/frontend/src/scenes/inbox/components/detail/ReportDetail.tsx
index 7b9dd1094761..2758f0202009 100644
--- a/frontend/src/scenes/inbox/components/detail/ReportDetail.tsx
+++ b/frontend/src/scenes/inbox/components/detail/ReportDetail.tsx
@@ -36,7 +36,16 @@ import { ConventionalCommitScopeTag } from '../cards/ReportCard'
import { CommitContent } from './artefactTypes'
import { DetailSection } from './DetailSection'
import { DiscussReportButton } from './DiscussReportButton'
-import { PullRequestBranchTag, PullRequestDiffPanel } from './PullRequestDiffPanel'
+import { PrChecksSection } from './PrChecksSection'
+import { PrCommentsSection } from './PrCommentsSection'
+import {
+ PullRequestBranchTag,
+ PullRequestBranchTagSkeleton,
+ PullRequestDiffPanel,
+ PullRequestDiffPending,
+ PullRequestDiffStat,
+ PullRequestDiffStatSkeleton,
+} from './PullRequestDiffPanel'
import { ReportActivitySection } from './ReportActivitySection'
import { useReportDetailActions } from './ReportDetailActions'
import { ReportTasksSection } from './ReportTasksSection'
@@ -249,12 +258,20 @@ interface InboxDetailFrameProps {
tab: InboxTabKey
/** Summary section heading icon + title. */
summary: { icon: ReactNode; title: string }
+ /** Content rendered in the main column directly under the Summary (e.g. the PR conversation). */
+ summaryFooter?: ReactNode
/** Extra primary action(s) rendered after the shared report actions. */
primaryAction?: ReactNode
- /** Diff body. When present, the overview and this render behind two tabs (GitHub-style PR view). */
+ /** Whether to render the Overview / Files changed tab bar. Driven by whether the report has a PR
+ * (known immediately), not by whether the diff has loaded — so the tab bar doesn't pop in a beat
+ * later and shift the layout. */
+ showFilesTab?: boolean
+ /** Diff body rendered under the "Files changed" tab (may be a skeleton while the commit artefact loads). */
diffSection?: ReactNode
/** Branch tag shown in the "Files changed" tab label, so the tab signals there's code behind it. */
diffBranchTag?: ReactNode
+ /** +/- line-count stat shown in the "Files changed" tab label, right of the branch. */
+ diffStat?: ReactNode
/** Extra sections (Tasks, Reviewers) – defaults applied by callers. */
children?: ReactNode
}
@@ -269,17 +286,20 @@ export function InboxDetailFrame({
report,
tab,
summary,
+ summaryFooter,
primaryAction,
+ showFilesTab,
diffSection,
diffBranchTag,
+ diffStat,
children,
}: InboxDetailFrameProps): JSX.Element {
const { reportSignals, reportSignalsLoading, priorityExplanation, actionabilityExplanation } = useValues(
inboxReportDetailLogic({ reportId: report.id, report })
)
- // GitHub-style PR view: when a diff is present, the overview and the diff live behind two tabs.
+ // GitHub-style PR view: when the report has a PR, the overview and the diff live behind two tabs.
const [activeDetailTab, setActiveDetailTab] = useState<'overview' | 'files'>('overview')
- const hasDiff = !!diffSection
+ const hasDiff = !!showFilesTab
const signals = reportSignals ?? []
const evidenceCount = reportSignals !== null ? signals.length : report.signal_count
const hasEvidence = evidenceCount > 0
@@ -305,7 +325,7 @@ export function InboxDetailFrame({
const overviewBody = (
<div className="grid grid-cols-1 @5xl:grid-cols-[minmax(0,80ch)_minmax(22rem,1fr)] gap-5">
- <div className="min-w-0">
+ <div className="min-w-0 flex flex-col gap-5">
<DetailSection icon={summary.icon} title={summary.title}>
{report.summary ? (
<LemonMarkdown
@@ -320,6 +340,7 @@ export function InboxDetailFrame({
</p>
)}
</DetailSection>
+ {summaryFooter}
</div>
<div className="flex flex-col min-w-0 gap-5">
@@ -443,6 +464,7 @@ export function InboxDetailFrame({
label: (
<span className="flex items-center gap-1.5">
<span>Files changed</span>
+ {diffStat}
{diffBranchTag}
</span>
),
@@ -469,7 +491,7 @@ function prFilesUrl(prUrl: string): string {
* the branch's diff against the default branch alongside the overview. Runs keep their own `AgentRunDetail`.
*/
export function ReportDetail({ report, tab }: { report: SignalReport; tab: InboxTabKey }): JSX.Element {
- const { latestCommitArtefact } = useValues(inboxReportDetailLogic({ reportId: report.id, report }))
+ const { latestCommitArtefact, reportArtefacts } = useValues(inboxReportDetailLogic({ reportId: report.id, report }))
const prUrl = safeHttpUrl(report.implementation_pr_url)
const prRef = prUrl ? parsePrUrlParts(prUrl) : null
@@ -479,6 +501,10 @@ export function ReportDetail({ report, tab }: { report: SignalReport; tab: Inbox
// tab when that artefact carries the repo + branch the diff endpoint needs.
const commit = latestCommitArtefact ? (latestCommitArtefact.content as CommitContent) : null
const canDiff = !!(commit?.repository && commit?.branch)
+ // A PR-bearing report always gets the tab bar right away — driven by `hasPr` (immediate) rather than
+ // the diff artefact (a beat later), so the tabs don't pop in and shift the layout. While the commit
+ // artefact is still loading, the tab label and body show skeletons.
+ const artefactsLoaded = reportArtefacts !== null
return (
<InboxDetailFrame
@@ -499,14 +525,33 @@ export function ReportDetail({ report, tab }: { report: SignalReport; tab: Inbox
</LemonButton>
) : undefined
}
+ showFilesTab={hasPr || canDiff}
diffSection={
- canDiff && commit && latestCommitArtefact ? (
+ canDiff && commit ? (
<PullRequestDiffPanel report={report} commit={commit} />
+ ) : hasPr ? (
+ <PullRequestDiffPending artefactsLoaded={artefactsLoaded} />
) : undefined
}
diffBranchTag={
- canDiff && commit && latestCommitArtefact ? <PullRequestBranchTag commit={commit} /> : undefined
+ canDiff && commit ? (
+ <PullRequestBranchTag commit={commit} />
+ ) : hasPr && !artefactsLoaded ? (
+ <PullRequestBranchTagSkeleton />
+ ) : undefined
+ }
+ diffStat={
+ canDiff && commit ? (
+ <PullRequestDiffStat report={report} commit={commit} />
+ ) : hasPr && !artefactsLoaded ? (
+ <PullRequestDiffStatSkeleton />
+ ) : undefined
}
- />
+ // The PR conversation sits under the Summary as primary content; CI checks stay in the
+ // sidebar. Both drop themselves when there's nothing to show.
+ summaryFooter={hasPr ? <PrCommentsSection report={report} /> : undefined}
+ >
+ {hasPr && <PrChecksSection report={report} />}
+ </InboxDetailFrame>
)
}
diff --git a/frontend/src/scenes/inbox/components/detail/SuggestedReviewersSection.tsx b/frontend/src/scenes/inbox/components/detail/SuggestedReviewersSection.tsx
index e7fcbfc0b346..b5b2194cec0e 100644
--- a/frontend/src/scenes/inbox/components/detail/SuggestedReviewersSection.tsx
+++ b/frontend/src/scenes/inbox/components/detail/SuggestedReviewersSection.tsx
@@ -245,7 +245,8 @@ function ReviewerRow({
)
return (
- <div className="group flex items-start gap-2 rounded px-1.5 py-1.5 transition-colors hover:bg-fill-highlight-50">
+ <div className="group flex items-start gap-2 rounded px-1.5 py-1.5">
+ {/* no row hover: the row isn't clickable, only the remove button (revealed on group hover) is */}
<Tooltip
title={
reviewer.user
diff --git a/frontend/src/scenes/inbox/logics/inboxReportDetailLogic.ts b/frontend/src/scenes/inbox/logics/inboxReportDetailLogic.ts
index b0a8d70ddb3a..ec12f40bc5e9 100644
--- a/frontend/src/scenes/inbox/logics/inboxReportDetailLogic.ts
+++ b/frontend/src/scenes/inbox/logics/inboxReportDetailLogic.ts
@@ -21,9 +21,17 @@ import { teamLogic } from 'scenes/teamLogic'
import { userLogic } from 'scenes/userLogic'
import { Task, TaskRunStatus } from 'products/posthog_ai/frontend/types/taskTypes'
-import { signalsReportsSignalsRetrieve } from 'products/signals/frontend/generated/api'
-import { signalsReportArtefactsDiff } from 'products/signals/frontend/generated/api'
-import type { CommitDiffResponseApi } from 'products/signals/frontend/generated/api.schemas'
+import {
+ signalsReportArtefactsDiff,
+ signalsReportPrChecks,
+ signalsReportPrComments,
+ signalsReportsSignalsRetrieve,
+} from 'products/signals/frontend/generated/api'
+import type {
+ CommitDiffResponseApi,
+ PullRequestCheckApi,
+ PullRequestCommentApi,
+} from 'products/signals/frontend/generated/api.schemas'
import type { SignalNodeApi } from '../../../../../products/signals/frontend/generated/api.schemas'
import {
@@ -77,6 +85,10 @@ const ACTIVE_STATUSES: SignalReportStatus[] = [
const REPORT_TASKS_POLL_INTERVAL_MS = 5000
+// PR CI checks refresh cadence while the detail is open — a running build's status stays current
+// without hammering GitHub. Mirrors the desktop PR-review view's 15s poll.
+const PR_CHECKS_POLL_INTERVAL_MS = 15000
+
/** Extract the PR url from a task's latest run output, if present. Mirrors desktop `getTaskPrUrl`. */
export function getTaskPrUrl(task: Task): string | null {
const prUrl = task.latest_run?.output?.pr_url
@@ -109,11 +121,18 @@ export interface inboxReportDetailLogicValues {
diffArtefactId: string | null
displayReviewers: EnrichedReviewer[] | null
expandedTaskIds: string[]
+ hasImplementationPr: boolean
isReResearch: boolean
isReportActive: boolean
isUpdatingReviewers: boolean
latestCommitArtefact: SignalReportArtefact | null
optimisticReviewers: EnrichedReviewer[] | null
+ prChecks: readonly PullRequestCheckApi[] | null
+ prChecksError: string | null
+ prChecksLoading: boolean
+ prComments: readonly PullRequestCommentApi[] | null
+ prCommentsError: string | null
+ prCommentsLoading: boolean
primaryTask: ReportTaskEntry | null
priorityExplanation: string | null
report: SignalReport | null
@@ -162,6 +181,36 @@ export interface inboxReportDetailLogicActions {
query?: string
}
}
+ loadPrChecks: () => any
+ loadPrChecksFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadPrChecksSuccess: (
+ prChecks: readonly PullRequestCheckApi[] | null,
+ payload?: any
+ ) => {
+ prChecks: readonly PullRequestCheckApi[] | null
+ payload?: any
+ }
+ loadPrComments: () => any
+ loadPrCommentsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadPrCommentsSuccess: (
+ prComments: readonly PullRequestCommentApi[] | null,
+ payload?: any
+ ) => {
+ prComments: readonly PullRequestCommentApi[] | null
+ payload?: any
+ }
loadReportArtefacts: () => any
loadReportArtefactsFailure: (
error: string,
@@ -259,6 +308,7 @@ export interface inboxReportDetailLogicMeta {
isUpdatingReviewers: (optimisticReviewers: EnrichedReviewer[] | null) => boolean
reportReviewers: (reportArtefacts: SignalReportArtefact[] | null) => EnrichedReviewer[] | null
isReportActive: (report: SignalReport | null) => boolean
+ hasImplementationPr: (report: SignalReport | null) => boolean
latestCommitArtefact: (reportArtefacts: SignalReportArtefact[] | null) => SignalReportArtefact | null
priorityExplanation: (reportArtefacts: SignalReportArtefact[] | null) => string | null
actionabilityExplanation: (reportArtefacts: SignalReportArtefact[] | null) => string | null
@@ -422,6 +472,36 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([
},
},
],
+ // CI checks on the report's implementation PR. Only fetched when the report has one; polled
+ // every 15s while the detail is mounted (see the `setReport` listener) so a running build's
+ // status stays current, mirroring the desktop PR-review view.
+ prChecks: [
+ null as readonly PullRequestCheckApi[] | null,
+ {
+ loadPrChecks: async () => {
+ const teamId = teamLogic.values.currentTeamId
+ if (!teamId) {
+ return null
+ }
+ const response = await signalsReportPrChecks(String(teamId), props.reportId)
+ return response.checks
+ },
+ },
+ ],
+ // Conversation + review comments on the report's implementation PR, merged chronologically.
+ prComments: [
+ null as readonly PullRequestCommentApi[] | null,
+ {
+ loadPrComments: async () => {
+ const teamId = teamLogic.values.currentTeamId
+ if (!teamId) {
+ return null
+ }
+ const response = await signalsReportPrComments(String(teamId), props.reportId)
+ return response.comments
+ },
+ },
+ ],
})),
reducers({
@@ -478,6 +558,24 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([
loadReportDiff: (_, { artefactId }) => artefactId,
},
],
+ // Human-readable PR checks/comments load failures (kea-loaders only exposes a boolean flag).
+ // A failure usually means the branch/PR was deleted or the GitHub integration lost access.
+ prChecksError: [
+ null as string | null,
+ {
+ loadPrChecks: () => null,
+ loadPrChecksSuccess: () => null,
+ loadPrChecksFailure: () => "Couldn't load the PR checks from GitHub.",
+ },
+ ],
+ prCommentsError: [
+ null as string | null,
+ {
+ loadPrComments: () => null,
+ loadPrCommentsSuccess: () => null,
+ loadPrCommentsFailure: () => "Couldn't load the PR comments from GitHub.",
+ },
+ ],
}),
selectors({
@@ -504,6 +602,11 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([
(s) => [s.report],
(report: SignalReport | null): boolean => (report ? ACTIVE_STATUSES.includes(report.status) : false),
],
+ // Whether the report has a shipped implementation PR — gates the PR checks/comments fetch + poll.
+ hasImplementationPr: [
+ (s) => [s.report],
+ (report: SignalReport | null): boolean => !!report?.implementation_pr_url,
+ ],
// The most recent `commit` artefact — its branch is treated as the report's branch to diff
// against the repository default branch. A report's code work may span several pushes; the
// latest commit's branch tip is the current state worth inspecting.
@@ -669,6 +772,17 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([
} else {
cache.disposables.dispose('reportTasksPoll')
}
+ // Load the PR checks/comments once the report has a shipped PR. The recurring checks poll
+ // is registered once in `afterMount` (not here) so it isn't torn down and restarted every
+ // time the shell hands us a fresh `report` prop — which would starve the 15s cadence.
+ if (values.hasImplementationPr) {
+ if (values.prChecks === null && !values.prChecksLoading) {
+ actions.loadPrChecks()
+ }
+ if (values.prComments === null && !values.prCommentsLoading) {
+ actions.loadPrComments()
+ }
+ }
},
})),
@@ -679,12 +793,24 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([
}
}),
- afterMount(({ actions, props }) => {
+ afterMount(({ actions, props, values, cache }) => {
// `loadReportTasks` is cascaded from `loadReportArtefactsSuccess`, so it isn't called here.
actions.loadReportArtefacts()
actions.loadReportSignals()
actions.loadAvailableReviewers()
// Seed the report from props so polling is gated on its status from the first tick.
actions.setReport(props.report ?? null)
+ // Register the PR-checks poll once for the lifetime of the mount — the tick re-checks whether
+ // the report has a PR, so it stays correct as the report prop churns without the interval ever
+ // being torn down and restarted (which would keep resetting the 15s cadence). Auto-disposed on
+ // unmount / hidden tab.
+ cache.disposables.add(() => {
+ const interval = setInterval(() => {
+ if (values.hasImplementationPr) {
+ actions.loadPrChecks()
+ }
+ }, PR_CHECKS_POLL_INTERVAL_MS)
+ return () => clearInterval(interval)
+ }, 'prChecksPoll')
}),
])
diff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.py
index f55f7a152c89..ea8867ac119e 100644
--- a/posthog/models/github_integration_base.py
+++ b/posthog/models/github_integration_base.py
@@ -10,7 +10,7 @@ import uuid
from collections.abc import Mapping
from dataclasses import dataclass
from datetime import datetime
-from typing import Any, Literal, cast
+from typing import Any, Literal, TypedDict, cast
from urllib.parse import urlparse
from django.conf import settings
@@ -48,6 +48,26 @@ GITHUB_BRANCH_CACHE_TIMEOUT_SECONDS = 60 * 60 * 24
INSTALLATION_UNAVAILABLE_SINCE_CONFIG_KEY = "installation_unavailable_since"
+class NormalizedPRComment(TypedDict):
+ """Wire shape for a PR comment shared by the read path and the review-comment write endpoints."""
+
+ id: str
+ author: str | None
+ author_avatar_url: str | None
+ body: str
+ created_at: str | None
+ url: str | None
+ comment_type: str
+ # Diff-anchor fields are only populated for review comments (None for conversation comments).
+ path: str | None
+ line: int | None
+ start_line: int | None
+ side: str | None
+ diff_hunk: str | None
+ in_reply_to_id: str | None
+ commit_id: str | None
+
+
@dataclass(frozen=True)
class GitHubCommitAuthor:
login: str
@@ -528,6 +548,49 @@ class GitHubIntegrationBase:
logger.warning("GitHubIntegration: installation GET failed", url=url, exc_info=True)
return None
+ def _installation_authenticated_get_pages(
+ self,
+ url: str,
+ *,
+ endpoint: str,
+ params: dict[str, str | int] | None = None,
+ timeout: int = 10,
+ ) -> tuple[list[requests.Response], bool]:
+ """Follow GitHub's trusted ``next`` links and report whether every page was fetched."""
+ responses: list[requests.Response] = []
+ next_url = url
+ next_params = params
+ seen_urls: set[str] = set()
+
+ while True:
+ if next_url in seen_urls:
+ return responses, False
+ seen_urls.add(next_url)
+ response = self._installation_authenticated_get(
+ next_url,
+ endpoint=endpoint,
+ params=next_params,
+ timeout=timeout,
+ )
+ if response is None:
+ return responses, False
+ responses.append(response)
+ if response.status_code != 200:
+ return responses, False
+
+ links = getattr(response, "links", None)
+ next_link = links.get("next") if isinstance(links, dict) else None
+ if next_link is None:
+ return responses, True
+ next_link_url = next_link.get("url") if isinstance(next_link, dict) else None
+ if not isinstance(next_link_url, str):
+ return responses, False
+ parsed_next_url = urlparse(next_link_url)
+ if parsed_next_url.scheme != "https" or parsed_next_url.netloc != "api.github.com":
+ return responses, False
+ next_url = next_link_url
+ next_params = None
+
def _installation_authenticated_patch(
self,
url: str,
@@ -930,6 +993,156 @@ class GitHubIntegrationBase:
owner, repo, pr_number = parsed
return self.comment_on_pull_request(f"{owner}/{repo}", pr_number, body)
+ def get_pull_request_checks(self, repository: str, pr_number: int) -> dict[str, Any]:
+ """Fetch the CI status for a PR — GitHub Actions check runs plus commit statuses from external
+ CI and GitHub Apps, merged into one normalized list (mirrors the checks GitHub shows on the PR page).
+
+ Returns ``{"success": True, "checks": [...]}`` on success, or ``{"success": False, "error": ...}``
+ on a handled failure. Rate limits raise :class:`GitHubRateLimitError`.
+ """
+ pr = self.get_pull_request(repository, pr_number)
+ if not pr.get("success"):
+ return {"success": False, "error": pr.get("error", "Failed to fetch pull request")}
+ head_sha = pr.get("head_sha")
+ if not head_sha:
+ return {"success": False, "error": "Pull request has no head commit"}
+ repo_path = repository if "/" in repository else f"{self.organization()}/{repository}"
+
+ checks: list[dict[str, Any]] = []
+
+ # GitHub Actions (and any Checks-API app) — the primary source for a modern repo.
+ runs_responses, runs_complete = self._installation_authenticated_get_pages(
+ f"https://api.github.com/repos/{repo_path}/commits/{head_sha}/check-runs",
+ endpoint="/repos/{owner}/{repo}/commits/{ref}/check-runs",
+ params={"per_page": 100},
+ )
+ if not runs_complete:
+ return {"success": False, "error": "GitHub could not return every check run"}
+ for runs_response in runs_responses:
+ try:
+ runs_body = runs_response.json()
+ except Exception:
+ logger.warning("GitHubIntegration: check-runs non-JSON response", repository=repo_path)
+ runs_body = {}
+ for run in (runs_body.get("check_runs") if isinstance(runs_body, dict) else None) or []:
+ if not isinstance(run, dict):
+ continue
+ checks.append(
+ {
+ "name": run.get("name") or "check",
+ "status": run.get("status"),
+ "conclusion": run.get("conclusion"),
+ "url": run.get("html_url") or run.get("details_url"),
+ }
+ )
+
+ # Commit statuses remain the mechanism used by external CI and GitHub Apps, including our Visual
+ # Review integration. The Statuses API returns them separately from Checks-API check runs.
+ status_responses, statuses_complete = self._installation_authenticated_get_pages(
+ f"https://api.github.com/repos/{repo_path}/commits/{head_sha}/status",
+ endpoint="/repos/{owner}/{repo}/commits/{ref}/status",
+ params={"per_page": 100},
+ )
+ if not statuses_complete:
+ return {"success": False, "error": "GitHub could not return every commit status"}
+ for status_response in status_responses:
+ try:
+ status_body = status_response.json()
+ except Exception:
+ logger.warning("GitHubIntegration: commit-status non-JSON response", repository=repo_path)
+ status_body = {}
+ for st in (status_body.get("statuses") if isinstance(status_body, dict) else None) or []:
+ if not isinstance(st, dict):
+ continue
+ mapped_status, mapped_conclusion = self._map_commit_status_state(st.get("state"))
+ checks.append(
+ {
+ "name": st.get("context") or "status",
+ "status": mapped_status,
+ "conclusion": mapped_conclusion,
+ "url": st.get("target_url"),
+ }
+ )
+
+ return {"success": True, "checks": checks}
+
+ @staticmethod
+ def _map_commit_status_state(state: str | None) -> tuple[str, str | None]:
+ """Map a commit-status ``state`` onto the check-run ``(status, conclusion)`` shape."""
+ if state == "success":
+ return "completed", "success"
+ if state in ("failure", "error"):
+ return "completed", "failure"
+ return "in_progress", None
+
+ @staticmethod
+ def normalize_pr_comment(raw: object, comment_type: str) -> NormalizedPRComment | None:
+ """Shape a raw GitHub comment into the wire contract."""
+ if not isinstance(raw, dict):
+ return None
+ user = raw.get("user") or {}
+ is_review = comment_type == "review"
+ return {
+ # Direct access on the primary key: a GitHub comment always carries an `id`, and
+ # coercing a missing one to the string "None" would collide as a React key downstream.
+ "id": str(raw["id"]),
+ "author": user.get("login"),
+ "author_avatar_url": user.get("avatar_url"),
+ "body": raw.get("body") or "",
+ "created_at": raw.get("created_at"),
+ "url": raw.get("html_url"),
+ "comment_type": comment_type,
+ # Only review comments are anchored to a file position in the diff.
+ "path": raw.get("path") if is_review else None,
+ "line": raw.get("line") if is_review else None,
+ "start_line": raw.get("start_line") if is_review else None,
+ "side": raw.get("side") if is_review else None,
+ "diff_hunk": raw.get("diff_hunk") if is_review else None,
+ "in_reply_to_id": str(raw["in_reply_to_id"]) if is_review and raw.get("in_reply_to_id") else None,
+ "commit_id": raw.get("commit_id") if is_review else None,
+ }
+
+ def get_pull_request_comments(self, repository: str, pr_number: int) -> dict[str, Any]:
+ """Fetch a PR's conversation comments and inline review comments, merged chronologically.
+
+ Returns ``{"success": True, "comments": [...]}`` on success, or ``{"success": False, "error": ...}``
+ on a handled failure. Rate limits raise :class:`GitHubRateLimitError`. Best-effort per source:
+ a failure fetching one comment kind still returns whatever the other kind yielded.
+ """
+ repo_path = repository if "/" in repository else f"{self.organization()}/{repository}"
+
+ comments: list[NormalizedPRComment] = []
+ for path, comment_type, endpoint in (
+ (f"issues/{pr_number}/comments", "conversation", "/repos/{owner}/{repo}/issues/{issue_number}/comments"),
+ (f"pulls/{pr_number}/comments", "review", "/repos/{owner}/{repo}/pulls/{pull_number}/comments"),
+ ):
+ responses, _complete = self._installation_authenticated_get_pages(
+ f"https://api.github.com/repos/{repo_path}/{path}",
+ endpoint=endpoint,
+ params={"per_page": 100},
+ )
+ for response in responses:
+ if response.status_code != 200:
+ continue
+ try:
+ body = response.json()
+ except Exception:
+ logger.warning(
+ "GitHubIntegration: get_pull_request_comments non-JSON response", repository=repo_path
+ )
+ continue
+ if not isinstance(body, list):
+ continue
+ for raw in body:
+ normalized = self.normalize_pr_comment(raw, comment_type)
+ if normalized is None:
+ continue
+ comments.append(normalized)
+
+ # Merge both streams into a single chronological thread; entries without a timestamp sort last.
+ comments.sort(key=lambda c: c.get("created_at") or "")
+ return {"success": True, "comments": comments}
+
def find_pull_request_urls_for_branch(self, repository: str, branch: str) -> list[str]:
"""Return the HTML URLs of open or closed PRs whose head is ``branch`` in ``repository``.
diff --git a/posthog/models/integration.py b/posthog/models/integration.py
index 833c108ee5df..bd0111d2fd16 100644
--- a/posthog/models/integration.py
+++ b/posthog/models/integration.py
@@ -3036,7 +3036,12 @@ class GitHubIntegration(GitHubIntegrationBase):
@classmethod
def first_for_team_repository(
- cls, team_id: int, repository: str, *, source: str | None = None
+ cls,
+ team_id: int,
+ repository: str,
+ *,
+ source: str | None = None,
+ priority: Priority | None = None,
) -> "GitHubIntegration | None":
"""First GitHub integration for the team whose installation can access ``repository`` (``owner/name``).
@@ -3048,7 +3053,7 @@ class GitHubIntegration(GitHubIntegrationBase):
if not _is_safe_github_repo_path(repository):
return None
for integration in Integration.objects.filter(team_id=team_id, kind="github").order_by("id"):
- github = cls(integration, source=source)
+ github = cls(integration, source=source, priority=priority)
if github.installation_can_access_repository(repository):
return github
return None
diff --git a/posthog/models/test/test_integration_model.py b/posthog/models/test/test_integration_model.py
index 31f3a80aa9d6..a92e4091992a 100644
--- a/posthog/models/test/test_integration_model.py
+++ b/posthog/models/test/test_integration_model.py
@@ -1524,6 +1524,190 @@ class TestGitHubIntegrationModel(BaseTest):
with patch.object(github, "_installation_authenticated_get", return_value=None):
assert github.get_open_pr_base_for_head("PostHog/posthog", "posthog-code/fix") is None
+ def test_get_pull_request_comments_merges_conversation_and_review_sorted(self):
+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
+ github = GitHubIntegration(integration)
+
+ def fake_get(url, **kwargs):
+ response = MagicMock(status_code=200)
+ if "/issues/" in url:
+ response.json.return_value = [
+ {
+ "id": 2,
+ "user": {"login": "bob", "avatar_url": "https://a/bob.png"},
+ "body": "second",
+ "created_at": "2026-07-06T10:00:00Z",
+ "html_url": "https://github.com/PostHog/posthog/pull/1#issuecomment-2",
+ }
+ ]
+ else: # /pulls/{n}/comments — review comments
+ response.json.return_value = [
+ {
+ "id": 1,
+ "user": {"login": "alice", "avatar_url": "https://a/alice.png"},
+ "body": "first",
+ "created_at": "2026-07-06T09:00:00Z",
+ "html_url": "https://github.com/PostHog/posthog/pull/1#discussion_r1",
+ "path": "posthog/models.py",
+ }
+ ]
+ return response
+
+ with patch.object(github, "_installation_authenticated_get", side_effect=fake_get):
+ result = github.get_pull_request_comments("PostHog/posthog", 1)
+
+ assert result["success"] is True
+ # Merged and sorted oldest-first across both sources; review comment carries its file path,
+ # conversation comment does not.
+ assert [(c["author"], c["comment_type"], c["path"]) for c in result["comments"]] == [
+ ("alice", "review", "posthog/models.py"),
+ ("bob", "conversation", None),
+ ]
+
+ def test_get_pull_request_comments_best_effort_when_one_source_fails(self):
+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
+ github = GitHubIntegration(integration)
+
+ def fake_get(url, **kwargs):
+ if "/issues/" in url:
+ return None # conversation fetch fails
+ response = MagicMock(status_code=200)
+ response.json.return_value = [
+ {"id": 1, "user": {"login": "alice"}, "body": "x", "created_at": "2026-07-06T09:00:00Z"}
+ ]
+ return response
+
+ with patch.object(github, "_installation_authenticated_get", side_effect=fake_get):
+ result = github.get_pull_request_comments("PostHog/posthog", 1)
+
+ assert result["success"] is True
+ assert [c["author"] for c in result["comments"]] == ["alice"]
+
+ @parameterized.expand(
+ [
+ ("success", "success", ("completed", "success")),
+ ("failure", "failure", ("completed", "failure")),
+ ("error", "error", ("completed", "failure")),
+ ("pending", "pending", ("in_progress", None)),
+ ("unknown", None, ("in_progress", None)),
+ ]
+ )
+ def test_map_commit_status_state(self, _name, state, expected):
+ assert GitHubIntegration._map_commit_status_state(state) == expected
+
+ def test_get_pull_request_checks_merges_check_runs_and_statuses(self):
+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
+ github = GitHubIntegration(integration)
+
+ def fake_get(url, **kwargs):
+ response = MagicMock(status_code=200)
+ if "/check-runs" in url:
+ response.json.return_value = {
+ "check_runs": [
+ {
+ "name": "unit",
+ "status": "completed",
+ "conclusion": "failure",
+ "html_url": "https://github.com/checks/1",
+ }
+ ]
+ }
+ else: # /status — legacy commit statuses
+ response.json.return_value = {
+ "statuses": [{"context": "buildkite", "state": "success", "target_url": "https://bk/1"}]
+ }
+ return response
+
+ with (
+ patch.object(github, "get_pull_request", return_value={"success": True, "head_sha": "abc123f"}),
+ patch.object(github, "_installation_authenticated_get", side_effect=fake_get),
+ ):
+ result = github.get_pull_request_checks("PostHog/posthog", 1)
+
+ assert result["success"] is True
+ assert result["checks"] == [
+ {"name": "unit", "status": "completed", "conclusion": "failure", "url": "https://github.com/checks/1"},
+ {"name": "buildkite", "status": "completed", "conclusion": "success", "url": "https://bk/1"},
+ ]
+
+ def test_get_pull_request_checks_follows_pagination(self):
+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
+ github = GitHubIntegration(integration)
+
+ def fake_get(url, **kwargs):
+ response = MagicMock(status_code=200)
+ response.links = {}
+ if "/check-runs" not in url:
+ response.json.return_value = {"statuses": []}
+ elif "page=2" in url:
+ response.json.return_value = {
+ "check_runs": [
+ {
+ "name": "second page",
+ "status": "completed",
+ "conclusion": "success",
+ }
+ ]
+ }
+ else:
+ response.json.return_value = {
+ "check_runs": [
+ {
+ "name": "first page",
+ "status": "completed",
+ "conclusion": "success",
+ }
+ ]
+ }
+ response.links = {
+ "next": {"url": "https://api.github.com/repos/PostHog/posthog/commits/abc123f/check-runs?page=2"}
+ }
+ return response
+
+ with (
+ patch.object(github, "get_pull_request", return_value={"success": True, "head_sha": "abc123f"}),
+ patch.object(github, "_installation_authenticated_get", side_effect=fake_get),
+ ):
+ result = github.get_pull_request_checks("PostHog/posthog", 1)
+
+ assert [check["name"] for check in result["checks"]] == ["first page", "second page"]
+
+ @parameterized.expand([("check_runs",), ("statuses",)])
+ def test_get_pull_request_checks_fails_when_later_page_is_unavailable(self, failing_source):
+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
+ github = GitHubIntegration(integration)
+
+ def fake_get(url, **kwargs):
+ source = "check_runs" if "/check-runs" in url else "statuses"
+ if source == failing_source and "page=2" in url:
+ return None
+
+ response = MagicMock(status_code=200)
+ response.links = {}
+ response.json.return_value = {"check_runs": []} if source == "check_runs" else {"statuses": []}
+ if source == failing_source:
+ next_path = "check-runs" if source == "check_runs" else "status"
+ response.links = {
+ "next": {"url": f"https://api.github.com/repos/PostHog/posthog/commits/abc123f/{next_path}?page=2"}
+ }
+ return response
+
+ with (
+ patch.object(github, "get_pull_request", return_value={"success": True, "head_sha": "abc123f"}),
+ patch.object(github, "_installation_authenticated_get", side_effect=fake_get),
+ ):
+ result = github.get_pull_request_checks("PostHog/posthog", 1)
+
+ expected_noun = "check run" if failing_source == "check_runs" else "commit status"
+ assert result == {"success": False, "error": f"GitHub could not return every {expected_noun}"}
+
+ def test_get_pull_request_checks_fails_when_pr_unavailable(self):
+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
+ github = GitHubIntegration(integration)
+ with patch.object(github, "get_pull_request", return_value={"success": False, "error": "nope"}):
+ result = github.get_pull_request_checks("PostHog/posthog", 1)
+ assert result["success"] is False
+
def test_get_diff_truncates_oversized_diff(self):
from posthog.models.integration import _MAX_DIFF_CHARS
diff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.py
index 8fa342c6f4a0..fa9ec1af1814 100644
--- a/products/signals/backend/serializers.py
+++ b/products/signals/backend/serializers.py
@@ -855,3 +855,88 @@ class CommitDiffResponseSerializer(serializers.Serializer):
read_only=True,
help_text="True when the diff was too large to return in full and has been truncated.",
)
+
+
+class PullRequestCheckSerializer(serializers.Serializer):
+ """One CI check on a pull request's head commit — a GitHub Actions check run or a legacy commit
+ status, normalized to a common shape."""
+
+ name = serializers.CharField(read_only=True, help_text="Check run name or status context.")
+ status = serializers.CharField(
+ read_only=True,
+ allow_null=True,
+ help_text="Lifecycle state: 'queued', 'in_progress', or 'completed'.",
+ )
+ conclusion = serializers.CharField(
+ read_only=True,
+ allow_null=True,
+ help_text="Outcome once completed: 'success', 'failure', 'neutral', 'cancelled', 'skipped', "
+ "'timed_out', or 'action_required'. Null while still running.",
+ )
+ url = serializers.CharField(
+ read_only=True, allow_null=True, help_text="Link to the check run / status detail on GitHub."
+ )
+
+
+class PullRequestChecksResponseSerializer(serializers.Serializer):
+ """Response for the PR checks endpoint — the CI status of a report's implementation PR."""
+
+ checks = PullRequestCheckSerializer(many=True, read_only=True)
+
+
+class PullRequestCommentSerializer(serializers.Serializer):
+ """One comment on a pull request — a conversation comment or an inline review comment."""
+
+ id = serializers.CharField(read_only=True, help_text="GitHub comment id.")
+ author = serializers.CharField(read_only=True, allow_null=True, help_text="Comment author's GitHub login.")
+ author_avatar_url = serializers.CharField(read_only=True, allow_null=True, help_text="Author's GitHub avatar URL.")
+ body = serializers.CharField(read_only=True, allow_blank=True, help_text="Comment body (GitHub-flavored markdown).")
+ created_at = serializers.CharField(read_only=True, allow_null=True, help_text="ISO 8601 creation timestamp.")
+ url = serializers.CharField(read_only=True, allow_null=True, help_text="Link to the comment on GitHub.")
+ comment_type = serializers.ChoiceField(
+ read_only=True,
+ choices=["conversation", "review"],
+ help_text="'conversation' for a PR discussion comment, 'review' for an inline code-review comment.",
+ )
+ path = serializers.CharField(
+ read_only=True, allow_null=True, help_text="File path the review comment is anchored to (review comments only)."
+ )
+ line = serializers.IntegerField(
+ read_only=True,
+ allow_null=True,
+ help_text="Line in the diff the review comment is anchored to — the end line for multi-line comments "
+ "(review comments only; null when the comment is outdated relative to the PR head).",
+ )
+ start_line = serializers.IntegerField(
+ read_only=True,
+ allow_null=True,
+ help_text="First line of a multi-line review comment's range (review comments only).",
+ )
+ side = serializers.ChoiceField(
+ read_only=True,
+ allow_null=True,
+ choices=["LEFT", "RIGHT"],
+ help_text="Diff side the review comment is anchored to: 'LEFT' = deletions, 'RIGHT' = additions "
+ "(review comments only).",
+ )
+ diff_hunk = serializers.CharField(
+ read_only=True,
+ allow_null=True,
+ help_text="Diff hunk excerpt the review comment applies to (review comments only).",
+ )
+ in_reply_to_id = serializers.CharField(
+ read_only=True,
+ allow_null=True,
+ help_text="Id of the thread root comment this one replies to; null for thread roots and conversation comments.",
+ )
+ commit_id = serializers.CharField(
+ read_only=True,
+ allow_null=True,
+ help_text="SHA of the commit the review comment was made against (review comments only).",
+ )
+
+
+class PullRequestCommentsResponseSerializer(serializers.Serializer):
+ """Response for the PR comments endpoint — conversation and review comments merged chronologically."""
+
+ comments = PullRequestCommentSerializer(many=True, read_only=True)
diff --git a/products/signals/backend/test/test_signal_report_api.py b/products/signals/backend/test/test_signal_report_api.py
index 898e0d2cb89c..8a56493d18d0 100644
--- a/products/signals/backend/test/test_signal_report_api.py
+++ b/products/signals/backend/test/test_signal_report_api.py
@@ -18,6 +18,8 @@ from parameterized import parameterized
from rest_framework import status
from social_django.models import UserSocialAuth
+from posthog.egress.github.transport import GitHubEgressBudgetExhausted
+from posthog.egress.limiter.policies import Priority
from posthog.models.team.team import Team
from products.signals.backend.implementation_pr import (
@@ -2324,3 +2326,131 @@ class TestSignalReportContentUpdateAPI(APIBaseTest):
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert "read-only" in response.json()["error"]
+
+
+class TestSignalReportPrEndpoints(APIBaseTest):
+ def _create_report(self) -> SignalReport:
+ return SignalReport.objects.create(
+ team=self.team,
+ status=SignalReport.Status.READY,
+ title="Test report",
+ summary="Test summary",
+ signal_count=1,
+ )
+
+ def _checks_url(self, report_id: str) -> str:
+ return f"/api/projects/{self.team.id}/signals/reports/{report_id}/pr_checks/"
+
+ def _comments_url(self, report_id: str) -> str:
+ return f"/api/projects/{self.team.id}/signals/reports/{report_id}/pr_comments/"
+
+ def test_pr_checks_404_when_report_has_no_implementation_pr(self):
+ report = self._create_report()
+ with patch(
+ "products.signals.backend.views.fetch_implementation_pr_urls_for_reports",
+ return_value={},
+ ):
+ response = self.client.get(self._checks_url(str(report.id)))
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+
+ def test_pr_checks_404_when_no_integration_can_access_repo(self):
+ report = self._create_report()
+ with (
+ patch(
+ "products.signals.backend.views.fetch_implementation_pr_urls_for_reports",
+ return_value={str(report.id): "https://github.com/PostHog/posthog/pull/7"},
+ ),
+ patch("products.signals.backend.views.GitHubIntegration.first_for_team_repository", return_value=None),
+ ):
+ response = self.client.get(self._checks_url(str(report.id)))
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+
+ def test_pr_checks_503_when_egress_budget_sheds_request(self):
+ report = self._create_report()
+ with (
+ patch(
+ "products.signals.backend.views.fetch_implementation_pr_urls_for_reports",
+ return_value={str(report.id): "https://github.com/PostHog/posthog/pull/7"},
+ ),
+ patch(
+ "products.signals.backend.views.GitHubIntegration.first_for_team_repository",
+ side_effect=GitHubEgressBudgetExhausted("shed"),
+ ),
+ ):
+ response = self.client.get(self._checks_url(str(report.id)))
+ assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE
+
+ def test_pr_checks_503_when_egress_budget_sheds_fetch(self):
+ report = self._create_report()
+ github = patch("products.signals.backend.views.GitHubIntegration.first_for_team_repository").start()
+ self.addCleanup(patch.stopall)
+ github.return_value.get_pull_request_checks.side_effect = GitHubEgressBudgetExhausted("shed")
+ with patch(
+ "products.signals.backend.views.fetch_implementation_pr_urls_for_reports",
+ return_value={str(report.id): "https://github.com/PostHog/posthog/pull/7"},
+ ):
+ response = self.client.get(self._checks_url(str(report.id)))
+ assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE
+
+ def test_pr_checks_success_returns_checks(self):
+ report = self._create_report()
+ github = patch("products.signals.backend.views.GitHubIntegration.first_for_team_repository").start()
+ self.addCleanup(patch.stopall)
+ checks = [{"name": "unit", "status": "completed", "conclusion": "success", "url": "https://gh/1"}]
+ github.return_value.get_pull_request_checks.return_value = {"success": True, "checks": checks}
+ with patch(
+ "products.signals.backend.views.fetch_implementation_pr_urls_for_reports",
+ return_value={str(report.id): "https://github.com/PostHog/posthog/pull/7"},
+ ):
+ response = self.client.get(self._checks_url(str(report.id)))
+ cached_response = self.client.get(self._checks_url(str(report.id)))
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json() == {"checks": checks}
+ assert cached_response.status_code == status.HTTP_200_OK
+ assert cached_response.json() == {"checks": checks}
+ # The PR number is parsed off the stored URL and passed through to the integration.
+ assert github.return_value.get_pull_request_checks.call_args.args == ("PostHog/posthog", 7)
+ github.return_value.get_pull_request_checks.assert_called_once()
+ github.assert_called_once_with(
+ self.team.id,
+ "PostHog/posthog",
+ source="signals_pr_detail",
+ priority=Priority.NORMAL,
+ )
+
+ def test_pr_checks_maps_upstream_failure_to_502(self):
+ report = self._create_report()
+ github = patch("products.signals.backend.views.GitHubIntegration.first_for_team_repository").start()
+ self.addCleanup(patch.stopall)
+ github.return_value.get_pull_request_checks.return_value = {"success": False, "error": "boom"}
+ with patch(
+ "products.signals.backend.views.fetch_implementation_pr_urls_for_reports",
+ return_value={str(report.id): "https://github.com/PostHog/posthog/pull/7"},
+ ):
+ response = self.client.get(self._checks_url(str(report.id)))
+ assert response.status_code == status.HTTP_502_BAD_GATEWAY
+
+ def test_pr_comments_success_returns_comments(self):
+ report = self._create_report()
+ github = patch("products.signals.backend.views.GitHubIntegration.first_for_team_repository").start()
+ self.addCleanup(patch.stopall)
+ comments = [
+ {
+ "id": "1",
+ "author": "alice",
+ "author_avatar_url": None,
+ "body": "lgtm",
+ "created_at": "2026-07-06T09:00:00Z",
+ "url": "https://gh/c/1",
+ "comment_type": "conversation",
+ "path": None,
+ }
+ ]
+ github.return_value.get_pull_request_comments.return_value = {"success": True, "comments": comments}
+ with patch(
+ "products.signals.backend.views.fetch_implementation_pr_urls_for_reports",
+ return_value={str(report.id): "https://github.com/PostHog/posthog/pull/7"},
+ ):
+ response = self.client.get(self._comments_url(str(report.id)))
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json() == {"comments": comments}
diff --git a/products/signals/backend/views.py b/products/signals/backend/views.py
index 3a7d07f269bb..0627416beee4 100644
--- a/products/signals/backend/views.py
+++ b/products/signals/backend/views.py
@@ -2,7 +2,7 @@ import json
import uuid
from collections.abc import Sequence
from datetime import UTC, timedelta
-from typing import cast
+from typing import Any, cast
from django.conf import settings
from django.core.cache import cache
@@ -49,7 +49,8 @@ from posthog.api.integration import github_rate_limited_response
from posthog.api.mixins import ValidatedRequest, validated_request
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.auth import InternalAPIAuthentication, OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication
-from posthog.egress.github.transport import GitHubRateLimitError
+from posthog.egress.github.transport import GitHubEgressBudgetExhausted, GitHubRateLimitError
+from posthog.egress.limiter.policies import Priority
from posthog.event_usage import report_user_action
from posthog.exceptions_capture import capture_exception
from posthog.models import Team, User
@@ -84,7 +85,10 @@ from products.signals.backend.billing import (
report_pr_is_merged,
)
from products.signals.backend.facade.api import emit_signal
-from products.signals.backend.implementation_pr import fetch_implementation_pr_state_for_reports
+from products.signals.backend.implementation_pr import (
+ fetch_implementation_pr_state_for_reports,
+ fetch_implementation_pr_urls_for_reports,
+)
from products.signals.backend.models import (
ArtefactAttribution,
AutonomyPriority,
@@ -105,6 +109,8 @@ from products.signals.backend.report_generation.resolve_reviewers import (
)
from products.signals.backend.serializers import (
CommitDiffResponseSerializer,
+ PullRequestChecksResponseSerializer,
+ PullRequestCommentsResponseSerializer,
ReportSignalsResponseSerializer,
SignalReportArtefactLogCreateSerializer,
SignalReportArtefactLogUpdateSerializer,
@@ -153,6 +159,7 @@ tracer = trace.get_tracer(__name__)
# signal that it's time to add real pagination, rather than silently truncating the list (the
# old behaviour, which capped at 100 and dropped everyone alphabetically after ~"M").
REVIEWER_PAGINATION_THRESHOLD = 1200
+PR_GITHUB_CACHE_SECONDS = 15
class EmitSignalSerializer(serializers.Serializer):
@@ -2077,6 +2084,168 @@ class SignalReportViewSet(
return Response({"status": "reingestion_started", "report_id": report_id}, status=status.HTTP_202_ACCEPTED)
+ def _resolve_report_pr_reference(self, report: SignalReport) -> tuple[str, int] | None:
+ """Resolve a report's implementation PR to ``(owner/repo, pr_number)``, or None if it has none
+ (or the stored URL isn't a parseable GitHub PR URL)."""
+ pr_url = fetch_implementation_pr_urls_for_reports([str(report.id)]).get(str(report.id))
+ if not pr_url:
+ return None
+ parsed = GitHubIntegration.parse_pull_request_url(pr_url)
+ if parsed is None:
+ return None
+ owner, repo, pr_number = parsed
+ return f"{owner}/{repo}", pr_number
+
+ @extend_schema(
+ responses={
+ 200: OpenApiResponse(
+ response=PullRequestChecksResponseSerializer,
+ description="The CI checks on the report's implementation pull request.",
+ ),
+ 404: OpenApiResponse(
+ description="Report has no implementation PR, or no GitHub integration can access it."
+ ),
+ 502: OpenApiResponse(description="GitHub could not return the checks."),
+ 503: OpenApiResponse(description="The GitHub egress budget is temporarily unavailable."),
+ },
+ summary="Fetch CI checks for a report's implementation PR",
+ description=(
+ "Fetch the CI status (GitHub Actions check runs and legacy commit statuses) of the pull "
+ "request the report's implementation task opened, via the team's GitHub integration."
+ ),
+ operation_id="signals_report_pr_checks",
+ )
+ @action(detail=True, methods=["get"], url_path="pr_checks", required_scopes=["task:read"])
+ def pr_checks(self, request: Request, *args, **kwargs) -> Response:
+ return self._pr_github_passthrough(
+ cast(SignalReport, self.get_object()), "get_pull_request_checks", "checks", "checks"
+ )
+
+ @extend_schema(
+ responses={
+ 200: OpenApiResponse(
+ response=PullRequestCommentsResponseSerializer,
+ description="Conversation and review comments on the report's implementation pull request.",
+ ),
+ 404: OpenApiResponse(
+ description="Report has no implementation PR, or no GitHub integration can access it."
+ ),
+ 502: OpenApiResponse(description="GitHub could not return the comments."),
+ 503: OpenApiResponse(description="The GitHub egress budget is temporarily unavailable."),
+ },
+ summary="Fetch comments for a report's implementation PR",
+ description=(
+ "Fetch the pull request's conversation comments and inline review comments, merged "
+ "chronologically, via the team's GitHub integration."
+ ),
+ operation_id="signals_report_pr_comments",
+ )
+ @action(detail=True, methods=["get"], url_path="pr_comments", required_scopes=["task:read"])
+ def pr_comments(self, request: Request, *args, **kwargs) -> Response:
+ return self._pr_github_passthrough(
+ cast(SignalReport, self.get_object()), "get_pull_request_comments", "comments", "comments"
+ )
+
+ def _pr_github_passthrough(self, report: SignalReport, fetch_name: str, key: str, noun: str) -> Response:
+ """Shared body for the ``pr_checks`` / ``pr_comments`` actions: resolve the report's PR and the
+ GitHub integration that can read it, call ``fetch_name`` on the client, and return ``{key: ...}``.
+ A missing PR/integration maps to 404, a rate limit to its response, and any other upstream GitHub
+ failure to 502 — an upstream hiccup never 500s the endpoint."""
+ reference = self._resolve_report_pr_reference(report)
+ if reference is None:
+ return Response(
+ {"error": "This report has no implementation pull request."},
+ status=status.HTTP_404_NOT_FOUND,
+ )
+ repository, pr_number = reference
+ cache_key = f"signals:pr-github:{self.team.id}:{repository}:{pr_number}:{fetch_name}"
+ cached_result = cache.get(cache_key)
+ if isinstance(cached_result, dict) and key in cached_result:
+ return Response({key: cached_result[key]})
+
+ github, repository, pr_number, error = self._github_for_report_pr(report, reference=reference)
+ if error is not None:
+ return error
+ assert github is not None # `error is None` guarantees a resolved integration
+ try:
+ result: dict[str, Any] = getattr(github, fetch_name)(repository, pr_number)
+ except GitHubRateLimitError as e:
+ return github_rate_limited_response(e)
+ except GitHubEgressBudgetExhausted:
+ return Response(
+ {"error": "GitHub is temporarily busy. Try again shortly."},
+ status=status.HTTP_503_SERVICE_UNAVAILABLE,
+ )
+ except Exception: # noqa: BLE001 — never let an upstream GitHub failure 500 this endpoint
+ logger.warning(f"signals pr {noun} fetch errored", repository=repository, pr_number=pr_number)
+ return Response(
+ {"error": f"GitHub could not return the {noun} for this pull request."},
+ status=status.HTTP_502_BAD_GATEWAY,
+ )
+ if not result.get("success"):
+ return Response(
+ {"error": result.get("error") or f"GitHub could not return the {noun} for this pull request."},
+ status=status.HTTP_502_BAD_GATEWAY,
+ )
+ cache.set(cache_key, result, timeout=PR_GITHUB_CACHE_SECONDS)
+ return Response({key: result[key]})
+
+ def _github_for_report_pr(
+ self,
+ report: SignalReport,
+ *,
+ reference: tuple[str, int] | None = None,
+ ) -> tuple[GitHubIntegration | None, str, int, Response | None]:
+ """Resolve the report's implementation PR and the GitHub integration that can read it.
+
+ Returns ``(github, repository, pr_number, error_response)`` — on any failure ``error_response``
+ is set (and should be returned as-is) and ``github`` is None. Mirrors the connection-boundary
+ scoping of the artefact `diff` action: access is bounded to repos the team's installation can
+ reach, not to a single per-report repository.
+ """
+ reference = reference or self._resolve_report_pr_reference(report)
+ if reference is None:
+ return (
+ None,
+ "",
+ 0,
+ Response(
+ {"error": "This report has no implementation pull request."},
+ status=status.HTTP_404_NOT_FOUND,
+ ),
+ )
+ repository, pr_number = reference
+ try:
+ github = GitHubIntegration.first_for_team_repository(
+ self.team.id,
+ repository,
+ source="signals_pr_detail",
+ priority=Priority.NORMAL,
+ )
+ except GitHubRateLimitError as e:
+ return None, repository, pr_number, github_rate_limited_response(e)
+ except GitHubEgressBudgetExhausted:
+ return (
+ None,
+ repository,
+ pr_number,
+ Response(
+ {"error": "GitHub is temporarily busy. Try again shortly."},
+ status=status.HTTP_503_SERVICE_UNAVAILABLE,
+ ),
+ )
+ if github is None:
+ return (
+ None,
+ repository,
+ pr_number,
+ Response(
+ {"error": f"No GitHub integration can access '{repository}'."},
+ status=status.HTTP_404_NOT_FOUND,
+ ),
+ )
+ return github, repository, pr_number, None
+
# `report_id` addresses a report's UUID primary key. Agents whose prompt only carries a
# `signal_id` sometimes pass that (e.g. `sig_praise`) here instead, so make the constraint
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index 4228e108f39c..70bd9aef95d4 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -241,6 +241,136 @@ export interface PatchedSignalReportContentUpdateApi {
summary?: string
}
+/**
+ * One CI check on a pull request's head commit — a GitHub Actions check run or a legacy commit
+ * status, normalized to a common shape.
+ */
+export interface PullRequestCheckApi {
+ /** Check run name or status context. */
+ readonly name: string
+ /**
+ * Lifecycle state: 'queued', 'in_progress', or 'completed'.
+ * @nullable
+ */
+ readonly status: string | null
+ /**
+ * Outcome once completed: 'success', 'failure', 'neutral', 'cancelled', 'skipped', 'timed_out', or 'action_required'. Null while still running.
+ * @nullable
+ */
+ readonly conclusion: string | null
+ /**
+ * Link to the check run / status detail on GitHub.
+ * @nullable
+ */
+ readonly url: string | null
+}
+
+/**
+ * Response for the PR checks endpoint — the CI status of a report's implementation PR.
+ */
+export interface PullRequestChecksResponseApi {
+ readonly checks: readonly PullRequestCheckApi[]
+}
+
+/**
+ * * `conversation` - conversation
+ * * `review` - review
+ */
+export type CommentTypeEnumApi = (typeof CommentTypeEnumApi)[keyof typeof CommentTypeEnumApi]
+
+export const CommentTypeEnumApi = {
+ Conversation: 'conversation',
+ Review: 'review',
+} as const
+
+/**
+ * * `LEFT` - LEFT
+ * * `RIGHT` - RIGHT
+ */
+export type SideEnumApi = (typeof SideEnumApi)[keyof typeof SideEnumApi]
+
+export const SideEnumApi = {
+ Left: 'LEFT',
+ Right: 'RIGHT',
+} as const
+
+/**
+ * One comment on a pull request — a conversation comment or an inline review comment.
+ */
+export interface PullRequestCommentApi {
+ /** GitHub comment id. */
+ readonly id: string
+ /**
+ * Comment author's GitHub login.
+ * @nullable
+ */
+ readonly author: string | null
+ /**
+ * Author's GitHub avatar URL.
+ * @nullable
+ */
+ readonly author_avatar_url: string | null
+ /** Comment body (GitHub-flavored markdown). */
+ readonly body: string
+ /**
+ * ISO 8601 creation timestamp.
+ * @nullable
+ */
+ readonly created_at: string | null
+ /**
+ * Link to the comment on GitHub.
+ * @nullable
+ */
+ readonly url: string | null
+ /** 'conversation' for a PR discussion comment, 'review' for an inline code-review comment.
+ *
+ * * `conversation` - conversation
+ * * `review` - review */
+ readonly comment_type: CommentTypeEnumApi
+ /**
+ * File path the review comment is anchored to (review comments only).
+ * @nullable
+ */
+ readonly path: string | null
+ /**
+ * Line in the diff the review comment is anchored to — the end line for multi-line comments (review comments only; null when the comment is outdated relative to the PR head).
+ * @nullable
+ */
+ readonly line: number | null
+ /**
+ * First line of a multi-line review comment's range (review comments only).
+ * @nullable
+ */
+ readonly start_line: number | null
+ /** Diff side the review comment is anchored to: 'LEFT' = deletions, 'RIGHT' = additions (review comments only).
+ *
+ * * `LEFT` - LEFT
+ * * `RIGHT` - RIGHT */
+ readonly side: SideEnumApi | null
+ /**
+ * Diff hunk excerpt the review comment applies to (review comments only).
+ * @nullable
+ */
+ readonly diff_hunk: string | null
+ /**
+ * Id of the thread root comment this one replies to; null for thread roots and conversation comments.
+ * @nullable
+ */
+ readonly in_reply_to_id: string | null
+ /**
+ * SHA of the commit the review comment was made against (review comments only).
+ * @nullable
+ */
+ readonly commit_id: string | null
+}
+
+/**
+ * Response for the PR comments endpoint — conversation and review comments merged chronologically.
+ */
+export interface PullRequestCommentsResponseApi {
+ readonly comments: readonly PullRequestCommentApi[]
+}
+
export interface SignalReportRefundRequestApi {
/** Why this PR is being refunded. One of: pr_incorrect (the PR doesn't address what the report promised), pr_not_useful (technically fine but not worth paying for), duplicate (covers work already charged elsewhere), other. Required — refund reviews key on it.
*
diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.ts
index 04dfacf7b4fb..995f3bdf66b6 100644
--- a/products/signals/frontend/generated/api.ts
+++ b/products/signals/frontend/generated/api.ts
@@ -30,6 +30,8 @@ import type {
PauseResponseApi,
PauseUntilRequestApi,
ProjectProfileApi,
+ PullRequestChecksResponseApi,
+ PullRequestCommentsResponseApi,
RememberRequestApi,
ReportSignalsResponseApi,
ScoutEmissionReportLinkApi,
@@ -220,6 +222,44 @@ export const signalsReportsPartialUpdate = async (
})
}
+export const getSignalsReportPrChecksUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/signals/reports/${id}/pr_checks/`
+}
+
+/**
+ * Fetch the CI status (GitHub Actions check runs and legacy commit statuses) of the pull request the report's implementation task opened, via the team's GitHub integration.
+ * @summary Fetch CI checks for a report's implementation PR
+ */
+export const signalsReportPrChecks = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<PullRequestChecksResponseApi> => {
+ return apiMutator<PullRequestChecksResponseApi>(getSignalsReportPrChecksUrl(projectId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getSignalsReportPrCommentsUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/signals/reports/${id}/pr_comments/`
+}
+
+/**
+ * Fetch the pull request's conversation comments and inline review comments, merged chronologically, via the team's GitHub integration.
+ * @summary Fetch comments for a report's implementation PR
+ */
+export const signalsReportPrComments = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<PullRequestCommentsResponseApi> => {
+ return apiMutator<PullRequestCommentsResponseApi>(getSignalsReportPrCommentsUrl(projectId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getSignalsReportsRefundCreateUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/signals/reports/${id}/refund/`
}
diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yaml
index 2e02ff047088..d34a6dbfc4d4 100644
--- a/products/signals/mcp/tools.yaml
+++ b/products/signals/mcp/tools.yaml
@@ -812,6 +812,12 @@ tools:
signals-report-artefacts-diff:
operation: signals_report_artefacts_diff
enabled: false
+ signals-report-pr-checks:
+ operation: signals_report_pr_checks
+ enabled: false
+ signals-report-pr-comments:
+ operation: signals_report_pr_comments
+ enabled: false
signals-reports-refund-create:
operation: signals_reports_refund_create
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 2362fb75b305..fc02faf8c53c 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -14890,6 +14890,18 @@ export namespace Schemas {
source_comment?: string | null;
}
+ /**
+ * * `conversation` - conversation
+ * * `review` - review
+ */
+ export type CommentTypeEnum = typeof CommentTypeEnum[keyof typeof CommentTypeEnum];
+
+
+ export const CommentTypeEnum = {
+ Conversation: 'conversation',
+ Review: 'review',
+ } as const;
+
/**
* Response for the `commit` artefact diff endpoint — the commit's branch rendered against the
* repository default branch.
@@ -55864,6 +55876,126 @@ export namespace Schemas {
max_proxy_records: number;
}
+ /**
+ * One CI check on a pull request's head commit — a GitHub Actions check run or a legacy commit
+ * status, normalized to a common shape.
+ */
+ export interface PullRequestCheck {
+ /** Check run name or status context. */
+ readonly name: string;
+ /**
+ * Lifecycle state: 'queued', 'in_progress', or 'completed'.
+ * @nullable
+ */
+ readonly status: string | null;
+ /**
+ * Outcome once completed: 'success', 'failure', 'neutral', 'cancelled', 'skipped', 'timed_out', or 'action_required'. Null while still running.
+ * @nullable
+ */
+ readonly conclusion: string | null;
+ /**
+ * Link to the check run / status detail on GitHub.
+ * @nullable
+ */
+ readonly url: string | null;
+ }
+
+ /**
+ * Response for the PR checks endpoint — the CI status of a report's implementation PR.
+ */
+ export interface PullRequestChecksResponse {
+ readonly checks: readonly PullRequestCheck[];
+ }
+
+ /**
+ * * `LEFT` - LEFT
+ * * `RIGHT` - RIGHT
+ */
+ export type SideEnum = typeof SideEnum[keyof typeof SideEnum];
+
+
+ export const SideEnum = {
+ Left: 'LEFT',
+ Right: 'RIGHT',
+ } as const;
+
+ /**
+ * One comment on a pull request — a conversation comment or an inline review comment.
+ */
+ export interface PullRequestComment {
+ /** GitHub comment id. */
+ readonly id: string;
+ /**
+ * Comment author's GitHub login.
+ * @nullable
+ */
+ readonly author: string | null;
+ /**
+ * Author's GitHub avatar URL.
+ * @nullable
+ */
+ readonly author_avatar_url: string | null;
+ /** Comment body (GitHub-flavored markdown). */
+ readonly body: string;
+ /**
+ * ISO 8601 creation timestamp.
+ * @nullable
+ */
+ readonly created_at: string | null;
+ /**
+ * Link to the comment on GitHub.
+ * @nullable
+ */
+ readonly url: string | null;
+ /** 'conversation' for a PR discussion comment, 'review' for an inline code-review comment.
+ *
+ * * `conversation` - conversation
+ * * `review` - review */
+ readonly comment_type: CommentTypeEnum;
+ /**
+ * File path the review comment is anchored to (review comments only).
+ * @nullable
+ */
+ readonly path: string | null;
+ /**
+ * Line in the diff the review comment is anchored to — the end line for multi-line comments (review comments only; null when the comment is outdated relative to the PR head).
+ * @nullable
+ */
+ readonly line: number | null;
+ /**
+ * First line of a multi-line review comment's range (review comments only).
+ * @nullable
+ */
+ readonly start_line: number | null;
+ /** Diff side the review comment is anchored to: 'LEFT' = deletions, 'RIGHT' = additions (review comments only).
+ *
+ * * `LEFT` - LEFT
+ * * `RIGHT` - RIGHT */
+ readonly side: SideEnum | null;
+ /**
+ * Diff hunk excerpt the review comment applies to (review comments only).
+ * @nullable
+ */
+ readonly diff_hunk: string | null;
+ /**
+ * Id of the thread root comment this one replies to; null for thread roots and conversation comments.
+ * @nullable
+ */
+ readonly in_reply_to_id: string | null;
+ /**
+ * SHA of the commit the review comment was made against (review comments only).
+ * @nullable
+ */
+ readonly commit_id: string | null;
+ }
+
+ /**
+ * Response for the PR comments endpoint — conversation and review comments merged chronologically.
+ */
+ export interface PullRequestCommentsResponse {
+ readonly comments: readonly PullRequestComment[];
+ }
+
export interface PushCISample {
/** Head commit SHA of this push (CI round). */
head_sha: string;