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(inbox): Add inline pull request reviews (#72242)

Michael Matlokab4d571046aa6
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 4394db8d9bd8..f586565dcc53 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6190,6 +6190,10 @@ snapshots:
hash: v1.k794b7964.296dae509cd0e88a9fef7adbba5235af5aef8b74c1077cb685bbd16b997c0dc6.pjqTvvIFWGFu-vDrjsSl9Fup4wniL2SMyMJNZFb3u8w
scenes-app-inbox-detail--pull-request-checks-passing--light:
hash: v1.k794b7964.8ba943a5363361d2601424e24d9289871bb4f42740c06dac27d8271def4a776d.R4C955XzaYHRnuIl4FBOZ9x7v3CiQ31wU6Hr5Br3xfY
+ scenes-app-inbox-detail--pull-request-inline-review--dark:
+ hash: v1.k794b7964.d89260b7e4099b17bebc621f5fab5f60a4ea1f530f4f6a994cf638007c080780.qIhljJsqUfvb5UPvvziAxf40gPoquL8TzLdLYm2yJbs
+ scenes-app-inbox-detail--pull-request-inline-review--light:
+ hash: v1.k794b7964.a0b8ef0276c5408dc8f4a446c5a5cdf9b38d3b352e49dc19395335ee6a8594a5.wjqDJQ8urXkDgA_OzMPYRbMjEi5G5Tt1lTr0rr__vPo
scenes-app-inbox-detail--report--dark:
hash: v1.k794b7964.b2bb8c879d3b8f8aea9692141c3e103aa28e2dee7c6bb0e0af0998303d3f7424.dNSsjRCetBaV1-kPWEMgmeS8vYUPKNkkrQiIvkCs2ss
scenes-app-inbox-detail--report--light:
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.ts
index 2bf033947352..0eb9609f9d8f 100644
--- a/frontend/src/generated/core/api.schemas.ts
+++ b/frontend/src/generated/core/api.schemas.ts
@@ -3732,6 +3732,11 @@ export interface UserGitHubIntegrationItemApi {
repository_selection?: string | null
/** Installation account metadata from GitHub. */
account?: UserGitHubAccountApi | null
+ /**
+ * The connected user's own GitHub login (distinct from the installation account).
+ * @nullable
+ */
+ github_login?: string | null
/** True when this installation id matches a team-level GitHub integration on the active project. */
uses_shared_installation: boolean
/** When this integration row was created. */
diff --git a/frontend/src/scenes/inbox/components/detail/InboxDetail.stories.tsx b/frontend/src/scenes/inbox/components/detail/InboxDetail.stories.tsx
index dabc91d9912d..3b09e1c4b20c 100644
--- a/frontend/src/scenes/inbox/components/detail/InboxDetail.stories.tsx
+++ b/frontend/src/scenes/inbox/components/detail/InboxDetail.stories.tsx
@@ -184,3 +184,85 @@ export const RunReady: Story = {
</Frame>
),
}
+
+// Inline review threads anchored onto the branch diff from `mockBranchDiff()`, with the viewer's own
+// GitHub identity connected so the composer, the edit/delete affordances and the reaction pills all
+// render. The default `detailMocks` return no comments and no personal connection, which is the
+// empty state the other PR stories cover.
+const reviewComment = (
+ overrides: Partial<Record<string, unknown>> & { id: string; body: string }
+): Record<string, unknown> => ({
+ author: 'octocat',
+ author_avatar_url: null,
+ created_at: '2026-06-11T09:00:00Z',
+ url: `https://github.com/PostHog/posthog/pull/12001#discussion_r${overrides.id}`,
+ comment_type: 'review',
+ path: 'frontend/src/scenes/invites/inviteLogic.ts',
+ line: 45,
+ start_line: null,
+ side: 'RIGHT',
+ diff_hunk: null,
+ in_reply_to_id: null,
+ commit_id: 'abc123',
+ reactions: [],
+ ...overrides,
+})
+
+const inlineReviewComments = [
+ reviewComment({
+ id: '1',
+ author: 'twixes',
+ body: 'Should this bail out before the toast fires? Right now an empty list still hits the loading state for a frame.',
+ reactions: [{ id: '11', content: '+1', user_login: 'octocat' }],
+ }),
+ reviewComment({
+ id: '2',
+ author: 'octocat',
+ body: 'Good catch, the early return covers it. Moved the guard above the toast.',
+ in_reply_to_id: '1',
+ created_at: '2026-06-11T09:12:00Z',
+ }),
+ reviewComment({
+ id: '3',
+ author: 'twixes',
+ body: 'Worth trimming here too, so a whitespace-only name does not count as a recipient.',
+ path: 'frontend/src/scenes/invites/InviteRow.tsx',
+ line: 12,
+ created_at: '2026-06-11T09:20:00Z',
+ reactions: [
+ { id: '31', content: 'heart', user_login: 'octocat' },
+ { id: '32', content: 'rocket', user_login: 'twixes' },
+ ],
+ }),
+]
+
+const inlineReviewMocks = mswDecorator({
+ get: {
+ '/api/projects/:id/signals/reports/:reportId/pr_comments/': () => [200, { comments: inlineReviewComments }],
+ '/api/users/@me/integrations/': () => [
+ 200,
+ {
+ results: [
+ {
+ id: 1,
+ installation_id: '12345',
+ repository_selection: 'all',
+ account: { type: 'Organization', name: 'PostHog' },
+ github_login: 'twixes',
+ uses_shared_installation: true,
+ created_at: '2026-05-01T00:00:00Z',
+ },
+ ],
+ },
+ ],
+ },
+})
+
+export const PullRequestInlineReview: Story = {
+ decorators: [inlineReviewMocks],
+ render: () => (
+ <Frame>
+ <PullRequestDetail report={pullRequestReports[0]} />
+ </Frame>
+ ),
+}
diff --git a/frontend/src/scenes/inbox/components/detail/InlineReviewThread.tsx b/frontend/src/scenes/inbox/components/detail/InlineReviewThread.tsx
new file mode 100644
index 000000000000..5d8e1901ee2f
--- /dev/null
+++ b/frontend/src/scenes/inbox/components/detail/InlineReviewThread.tsx
@@ -0,0 +1,448 @@
+import { useActions, useValues } from 'kea'
+import { KeyboardEvent, useState } from 'react'
+
+import { IconEllipsis, IconExternal, IconGithub, IconPencil, IconEmojiAdd, IconTrash } from '@posthog/icons'
+import { LemonButton, LemonMenu, LemonTextArea, Link, Popover, Tooltip } from '@posthog/lemon-ui'
+
+import { TZLabel } from 'lib/components/TZLabel'
+import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'
+import { urls } from 'scenes/urls'
+
+import type { PullRequestCommentReactionApi } from 'products/signals/frontend/generated/api.schemas'
+
+import {
+ ClientPullRequestComment,
+ DraftThread,
+ inboxReportDetailLogic,
+ InboxReportDetailLogicProps,
+ ReviewThread,
+ threadKey,
+} from '../../logics/inboxReportDetailLogic'
+
+// The card is dropped into @pierre/diffs' annotation slot, which spans the full row width under the
+// diff line (gutter included). Indent past the gutter and cap the width so a thread reads like a
+// focused conversation, not a full-bleed banner. Border color is per-variant so it never conflicts.
+const CARD_BASE =
+ 'pointer-events-auto my-1.5 ml-2 mr-3 max-w-[52rem] overflow-hidden rounded-lg border bg-surface-primary font-sans shadow-sm'
+
+// The reactions GitHub supports, in the order its own picker shows them, with the emoji we render.
+const REACTIONS: { content: string; emoji: string; label: string }[] = [
+ { content: '+1', emoji: '👍', label: 'thumbs up' },
+ { content: '-1', emoji: '👎', label: 'thumbs down' },
+ { content: 'laugh', emoji: '😄', label: 'laugh' },
+ { content: 'hooray', emoji: '🎉', label: 'hooray' },
+ { content: 'confused', emoji: '😕', label: 'confused' },
+ { content: 'heart', emoji: '❤️', label: 'heart' },
+ { content: 'rocket', emoji: '🚀', label: 'rocket' },
+ { content: 'eyes', emoji: '👀', label: 'eyes' },
+]
+/** GitHub-style add-reaction picker: a compact 3-column emoji grid in a popover — emoji only, no labels. */
+function ReactionPicker({ onPick }: { onPick: (content: string) => void }): JSX.Element {
+ const [open, setOpen] = useState(false)
+ return (
+ <Popover
+ visible={open}
+ onClickOutside={() => setOpen(false)}
+ placement="bottom-start"
+ overlay={
+ <div className="grid grid-cols-3 gap-0.5 p-1">
+ {REACTIONS.map((r) => (
+ <button
+ key={r.content}
+ type="button"
+ title={r.label}
+ aria-label={`React ${r.label}`}
+ onClick={() => {
+ onPick(r.content)
+ setOpen(false)
+ }}
+ className="flex size-8 items-center justify-center rounded text-base transition-colors hover:bg-fill-highlight-50"
+ >
+ {r.emoji}
+ </button>
+ ))}
+ </div>
+ }
+ >
+ <LemonButton
+ size="xsmall"
+ icon={<IconEmojiAdd />}
+ tooltip="Add reaction"
+ active={open}
+ onClick={() => setOpen((o) => !o)}
+ />
+ </Popover>
+ )
+}
+
+/** Reaction pills (grouped by emoji, the viewer's own highlighted) plus an add-reaction picker. */
+function ReactionBar({
+ logicProps,
+ comment,
+}: {
+ logicProps: InboxReportDetailLogicProps
+ comment: ClientPullRequestComment
+}): JSX.Element | null {
+ const { currentUserGithubLogin, hasPersonalGithub } = useValues(inboxReportDetailLogic(logicProps))
+ const { toggleReviewCommentReaction } = useActions(inboxReportDetailLogic(logicProps))
+ const reactions = comment.reactions ?? []
+ const pending = !!comment.pending
+
+ // Group by content → count + whether the viewer reacted, preserving GitHub's canonical order.
+ const groups = REACTIONS.map(({ content, emoji, label }) => {
+ const forContent = reactions.filter((r: PullRequestCommentReactionApi) => r.content === content)
+ return {
+ content,
+ emoji,
+ label,
+ count: forContent.length,
+ mine: forContent.some((r) => r.user_login === currentUserGithubLogin),
+ }
+ }).filter((g) => g.count > 0)
+
+ if (groups.length === 0 && (!hasPersonalGithub || pending)) {
+ return null
+ }
+
+ return (
+ <div className="flex flex-wrap items-center gap-1">
+ {groups.map((g) => (
+ <Tooltip key={g.content} title={g.mine ? `You reacted ${g.label}` : g.label}>
+ <button
+ type="button"
+ disabled={!hasPersonalGithub || pending}
+ onClick={() => toggleReviewCommentReaction(comment.id, g.content)}
+ className={`flex items-center gap-1 rounded-full border px-1.5 py-0.5 text-xs tabular-nums transition-colors disabled:opacity-60 ${
+ g.mine
+ ? 'border-accent bg-accent-highlight text-accent-primary'
+ : 'border-primary bg-surface-secondary text-secondary hover:border-secondary'
+ }`}
+ >
+ <span className="text-[0.8125rem] leading-none">{g.emoji}</span>
+ {g.count}
+ </button>
+ </Tooltip>
+ ))}
+ {hasPersonalGithub && !pending && (
+ <ReactionPicker onPick={(content) => toggleReviewCommentReaction(comment.id, content)} />
+ )}
+ </div>
+ )
+}
+
+/** One comment inside a thread: avatar, author, time, actions (own comments), markdown body, reactions. */
+function ThreadComment({
+ logicProps,
+ comment,
+}: {
+ logicProps: InboxReportDetailLogicProps
+ comment: ClientPullRequestComment
+}): JSX.Element {
+ const { currentUserGithubLogin, editingCommentId } = useValues(inboxReportDetailLogic(logicProps))
+ const { setEditingCommentId, editReviewComment, deleteReviewComment } = useActions(
+ inboxReportDetailLogic(logicProps)
+ )
+ const isMine = !!comment.author && comment.author === currentUserGithubLogin
+ const editing = editingCommentId === comment.id
+ const sending = comment.pending === 'sending'
+ const failed = comment.pending === 'failed'
+
+ return (
+ <div className={`flex gap-2.5 px-3 py-2.5 ${sending ? 'opacity-60' : ''}`}>
+ {comment.author_avatar_url ? (
+ <img
+ src={comment.author_avatar_url}
+ alt={comment.author ?? 'author'}
+ className="mt-0.5 size-5 shrink-0 rounded-full bg-fill-highlight-50"
+ loading="lazy"
+ />
+ ) : (
+ <span className="mt-0.5 size-5 shrink-0 rounded-full bg-fill-highlight-100" aria-hidden />
+ )}
+ <div className="flex min-w-0 flex-1 flex-col gap-1">
+ <div className="flex min-w-0 items-center gap-x-2 text-xs text-tertiary">
+ <span className="font-semibold text-secondary">{comment.author ?? 'Unknown'}</span>
+ {comment.created_at && !comment.pending && <TZLabel time={comment.created_at} />}
+ {sending && <span className="italic">Posting…</span>}
+ {failed && <span className="text-danger">Failed to post</span>}
+ <div className="ml-auto flex items-center gap-0.5">
+ {comment.url && (
+ <Link
+ to={comment.url}
+ target="_blank"
+ className="inline-flex items-center p-1 text-tertiary"
+ aria-label="Open on GitHub"
+ >
+ <IconExternal className="size-3.5" />
+ </Link>
+ )}
+ {isMine && !comment.pending && !editing && (
+ <LemonMenu
+ items={[
+ {
+ label: 'Edit',
+ icon: <IconPencil />,
+ onClick: () => setEditingCommentId(comment.id),
+ },
+ {
+ label: 'Delete',
+ icon: <IconTrash />,
+ status: 'danger',
+ onClick: () => deleteReviewComment(comment.id),
+ },
+ ]}
+ placement="bottom-end"
+ >
+ <LemonButton size="xsmall" icon={<IconEllipsis />} tooltip="Comment actions" />
+ </LemonMenu>
+ )}
+ </div>
+ </div>
+ {editing ? (
+ <CommentEditor
+ initialBody={comment.body}
+ onCancel={() => setEditingCommentId(null)}
+ onSave={(body) => editReviewComment(comment.id, body)}
+ />
+ ) : comment.body ? (
+ <LemonMarkdown className="text-[0.8125rem] leading-relaxed text-primary break-words" disableImages>
+ {comment.body}
+ </LemonMarkdown>
+ ) : (
+ <span className="text-xs italic text-tertiary">No description</span>
+ )}
+ {!editing && <ReactionBar logicProps={logicProps} comment={comment} />}
+ </div>
+ </div>
+ )
+}
+
+/** Inline editor for an existing comment: pre-filled textarea, ⌘⏎ to save, Escape to cancel. */
+function CommentEditor({
+ initialBody,
+ onCancel,
+ onSave,
+}: {
+ initialBody: string
+ onCancel: () => void
+ onSave: (body: string) => void
+}): JSX.Element {
+ const [body, setBody] = useState(initialBody)
+ const dirty = body.trim().length > 0 && body !== initialBody
+ const save = (): void => {
+ if (dirty) {
+ onSave(body.trim())
+ }
+ }
+ return (
+ <div className="flex flex-col gap-1.5">
+ <LemonTextArea
+ autoFocus
+ value={body}
+ onChange={setBody}
+ onPressCmdEnter={save}
+ onKeyDown={(e: KeyboardEvent<HTMLTextAreaElement>) => {
+ if (e.key === 'Escape') {
+ e.preventDefault()
+ onCancel()
+ }
+ }}
+ minRows={2}
+ maxRows={12}
+ className="text-[0.8125rem]"
+ />
+ <div className="flex items-center justify-end gap-1.5">
+ <LemonButton type="tertiary" size="xsmall" onClick={onCancel}>
+ Cancel
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ size="xsmall"
+ onClick={save}
+ disabledReason={!dirty ? 'Make a change first' : undefined}
+ >
+ Save
+ </LemonButton>
+ </div>
+ </div>
+ )
+}
+
+/** Borderless composer (the card is the frame): collapsed "Reply…" state, ⌘⏎ submit, in-flight guard. */
+function ThreadComposer({
+ logicProps,
+ composerKey,
+ placeholder,
+ startExpanded,
+ onCancel,
+ onSubmit,
+}: {
+ logicProps: InboxReportDetailLogicProps
+ composerKey: string
+ placeholder: string
+ /** Draft threads open straight into the textarea; existing threads start at the collapsed "Reply…" pill. */
+ startExpanded: boolean
+ onCancel?: () => void
+ onSubmit: (body: string) => void
+}): JSX.Element {
+ const { postingThreadKey, hasPersonalGithub } = useValues(inboxReportDetailLogic(logicProps))
+ const [expanded, setExpanded] = useState(startExpanded)
+ const [body, setBody] = useState('')
+ const posting = postingThreadKey === composerKey
+ const anyPosting = postingThreadKey !== null
+
+ if (!hasPersonalGithub) {
+ return (
+ <div className="flex items-center justify-between gap-2 bg-surface-secondary px-3 py-2">
+ <span className="text-xs text-tertiary">Comments post to GitHub as you</span>
+ <LemonButton
+ type="secondary"
+ size="xsmall"
+ icon={<IconGithub />}
+ to={urls.settings('user-personal-integrations')}
+ targetBlank
+ >
+ Connect GitHub
+ </LemonButton>
+ </div>
+ )
+ }
+
+ if (!expanded) {
+ return (
+ <div className="p-2">
+ <button
+ type="button"
+ onClick={() => setExpanded(true)}
+ className="w-full cursor-text rounded-md border border-primary bg-bg-light px-3 py-1.5 text-left text-xs text-tertiary transition-colors hover:border-secondary"
+ >
+ Reply…
+ </button>
+ </div>
+ )
+ }
+
+ const canSubmit = body.trim().length > 0 && !anyPosting
+ const submit = (): void => {
+ if (canSubmit) {
+ onSubmit(body.trim())
+ setBody('')
+ }
+ }
+ const cancel = (): void => (onCancel ? onCancel() : setExpanded(false))
+ const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>): void => {
+ if (e.key === 'Escape') {
+ e.preventDefault()
+ cancel()
+ }
+ }
+
+ return (
+ // One column: `pl-3` defines the left inset; the textarea's own horizontal padding is zeroed
+ // so its text and the footer below it start on the same line. `pr-2` pulls the footer's
+ // Cancel/Comment buttons in so they align neatly with the card's right edge.
+ <div className="flex flex-col gap-1.5 pl-3 pr-2 py-2">
+ <LemonTextArea
+ autoFocus
+ hideFocus
+ value={body}
+ onChange={setBody}
+ onPressCmdEnter={submit}
+ onKeyDown={handleKeyDown}
+ placeholder={placeholder}
+ minRows={2}
+ maxRows={12}
+ disabled={posting}
+ className="!bg-transparent !px-0 text-[0.8125rem]"
+ data-attr="inline-review-comment-textarea"
+ />
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-[0.6875rem] text-tertiary">Markdown · ⌘⏎ to comment</span>
+ <div className="flex items-center gap-1.5">
+ <LemonButton
+ type="tertiary"
+ size="xsmall"
+ onClick={cancel}
+ disabledReason={posting ? 'Posting…' : undefined}
+ >
+ Cancel
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ size="xsmall"
+ onClick={submit}
+ loading={posting}
+ disabledReason={
+ body.trim().length === 0
+ ? 'Write a comment first'
+ : anyPosting && !posting
+ ? 'Another comment is posting'
+ : undefined
+ }
+ data-attr="inline-review-comment-submit"
+ >
+ Comment
+ </LemonButton>
+ </div>
+ </div>
+ </div>
+ )
+}
+
+/** An existing review thread rendered inline under its diff line: comments + reply composer. */
+export function InlineReviewThread({
+ logicProps,
+ thread,
+}: {
+ logicProps: InboxReportDetailLogicProps
+ thread: ReviewThread
+}): JSX.Element {
+ const { postReviewComment } = useActions(inboxReportDetailLogic(logicProps))
+ const key = threadKey(thread)
+
+ return (
+ <div className={`${CARD_BASE} border-primary`}>
+ <div className="flex flex-col divide-y divide-primary">
+ {thread.comments.map((comment) => (
+ <ThreadComment key={comment.id} logicProps={logicProps} comment={comment} />
+ ))}
+ </div>
+ <div className="border-t border-primary bg-surface-secondary">
+ <ThreadComposer
+ logicProps={logicProps}
+ composerKey={key}
+ placeholder="Reply to this thread"
+ startExpanded={false}
+ onSubmit={(body) => postReviewComment({ body, inReplyTo: thread.rootId, key })}
+ />
+ </div>
+ </div>
+ )
+}
+
+/** A fresh, not-yet-posted thread on a diff line: just the composer, accent-framed and focused. */
+export function InlineDraftThread({
+ logicProps,
+ draft,
+}: {
+ logicProps: InboxReportDetailLogicProps
+ draft: DraftThread
+}): JSX.Element {
+ const { postReviewComment, closeDraftThread } = useActions(inboxReportDetailLogic(logicProps))
+ const key = threadKey(draft)
+
+ return (
+ <div className={`${CARD_BASE} border-accent`}>
+ <ThreadComposer
+ logicProps={logicProps}
+ composerKey={key}
+ placeholder="Leave a comment"
+ startExpanded
+ onCancel={closeDraftThread}
+ onSubmit={(body) =>
+ postReviewComment({ body, path: draft.path, line: draft.line, side: draft.side, key })
+ }
+ />
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/inbox/components/detail/PullRequestDiffPanel.tsx b/frontend/src/scenes/inbox/components/detail/PullRequestDiffPanel.tsx
index e13c922b2961..48fb7156f52e 100644
--- a/frontend/src/scenes/inbox/components/detail/PullRequestDiffPanel.tsx
+++ b/frontend/src/scenes/inbox/components/detail/PullRequestDiffPanel.tsx
@@ -1,13 +1,15 @@
-import { useValues } from 'kea'
-import { useMemo, useState } from 'react'
+import { type DiffLineAnnotation } from '@pierre/diffs'
+import { useActions, useValues } from 'kea'
+import { useCallback, useMemo, useState } from 'react'
-import { IconGitBranch } from '@posthog/icons'
+import { IconChat, IconGitBranch } from '@posthog/icons'
import { LemonSegmentedButton, LemonSkeleton, LemonTag, Tooltip } from '@posthog/lemon-ui'
-import { inboxReportDetailLogic } from '../../logics/inboxReportDetailLogic'
+import { DraftThread, inboxReportDetailLogic, ReviewThread, threadKey } from '../../logics/inboxReportDetailLogic'
import { SignalReport } from '../../types'
import { CommitContent } from './artefactTypes'
-import { PullRequestDiffView, summarizeDiff } from './PullRequestDiffView'
+import { InlineDraftThread, InlineReviewThread } from './InlineReviewThread'
+import { DiffAnnotationData, PullRequestDiffView, summarizeDiff } from './PullRequestDiffView'
const DIFF_STYLE_OPTIONS = [
{ value: 'unified' as const, label: 'Unified' },
@@ -103,17 +105,63 @@ export function PullRequestBranchTag({ commit }: { commit: CommitContent }): JSX
*/
export function PullRequestDiffPanel({ report, commit }: { report: SignalReport; commit: CommitContent }): JSX.Element {
const logicProps = useMemo(() => ({ reportId: report.id, report }), [report])
- const { reportDiff, reportDiffError } = useValues(inboxReportDetailLogic(logicProps))
+ const { reportDiff, reportDiffError, inlineThreadsByFile, inlineThreadCount, draftThread, hasImplementationPr } =
+ useValues(inboxReportDetailLogic(logicProps))
+ const { openDraftThread } = useActions(inboxReportDetailLogic(logicProps))
const [diffStyle, setDiffStyle] = useState<'unified' | 'split'>('unified')
const diffSummary = useMemo(
() => (reportDiff ? summarizeDiff(reportDiff.diff, commit.commit_sha) : null),
[reportDiff, commit.commit_sha]
)
+ // Threads and the draft become Pierre line annotations; resolving an annotation back to its
+ // thread goes through this map, so the annotation payload stays a plain string key.
+ const { annotationsByFile, threadsByKey } = useMemo(() => {
+ const annotations: Record<string, DiffLineAnnotation<DiffAnnotationData>[]> = {}
+ const byKey = new Map<string, ReviewThread>()
+ for (const [file, threads] of Object.entries(inlineThreadsByFile)) {
+ annotations[file] = threads.map((thread) => {
+ const key = threadKey(thread)
+ byKey.set(key, thread)
+ return {
+ side: thread.side === 'LEFT' ? ('deletions' as const) : ('additions' as const),
+ lineNumber: thread.line,
+ metadata: { kind: 'thread' as const, key },
+ }
+ })
+ }
+ if (draftThread) {
+ ;(annotations[draftThread.path] ??= []).push({
+ side: draftThread.side === 'LEFT' ? ('deletions' as const) : ('additions' as const),
+ lineNumber: draftThread.line,
+ metadata: { kind: 'draft' as const, key: threadKey(draftThread) },
+ })
+ }
+ return { annotationsByFile: annotations, threadsByKey: byKey }
+ }, [inlineThreadsByFile, draftThread])
+
+ const renderAnnotation = useCallback(
+ (annotation: DiffLineAnnotation<DiffAnnotationData>): JSX.Element | null => {
+ if (annotation.metadata.kind === 'draft') {
+ return draftThread ? <InlineDraftThread logicProps={logicProps} draft={draftThread} /> : null
+ }
+ const thread = threadsByKey.get(annotation.metadata.key)
+ return thread ? <InlineReviewThread logicProps={logicProps} thread={thread} /> : null
+ },
+ [draftThread, threadsByKey, logicProps]
+ )
+
+ const handleLineNumberClick = useCallback(
+ (file: string, line: number, side: 'LEFT' | 'RIGHT') => {
+ openDraftThread({ path: file, line, side } satisfies DraftThread)
+ },
+ [openDraftThread]
+ )
+
return (
<div className="flex flex-col gap-3">
<div className="flex items-center justify-between gap-3 min-w-0">
- <DiffToolbarSummary commit={commit} diffSummary={diffSummary} />
+ <DiffToolbarSummary commit={commit} diffSummary={diffSummary} inlineThreadCount={inlineThreadCount} />
<LemonSegmentedButton
size="small"
value={diffStyle}
@@ -131,7 +179,15 @@ export function PullRequestDiffPanel({ report, commit }: { report: SignalReport;
truncated={reportDiff.truncated}
cacheKey={commit.commit_sha}
diffStyle={diffStyle}
+ annotationsByFile={annotationsByFile}
+ renderAnnotation={renderAnnotation}
+ onLineNumberClick={hasImplementationPr ? handleLineNumberClick : undefined}
/>
+ {hasImplementationPr && (
+ <p className="m-0 text-[0.6875rem] text-tertiary">
+ Click a line number to comment. Comments post to the pull request as you.
+ </p>
+ )}
</>
) : (
<div className="flex flex-col gap-2">
@@ -147,17 +203,26 @@ export function PullRequestDiffPanel({ report, commit }: { report: SignalReport;
function DiffToolbarSummary({
commit,
diffSummary,
+ inlineThreadCount,
}: {
commit: CommitContent
diffSummary: ReturnType<typeof summarizeDiff>
+ inlineThreadCount: number
}): JSX.Element {
if (diffSummary) {
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.
+ // The +/- line stat lives in the "Files changed" tab label now, so the toolbar carries just
+ // the file count and (when present) the inline-thread count.
<div className="flex min-w-0 items-center gap-2 text-sm">
<span className="truncate text-secondary">{fileLabel}</span>
+ {inlineThreadCount > 0 && (
+ <span className="flex shrink-0 items-center gap-1 text-xs text-tertiary tabular-nums">
+ <IconChat className="size-3.5" />
+ {inlineThreadCount}
+ </span>
+ )}
</div>
)
}
diff --git a/frontend/src/scenes/inbox/components/detail/PullRequestDiffView.tsx b/frontend/src/scenes/inbox/components/detail/PullRequestDiffView.tsx
index beafaefa9395..6468243e8fc8 100644
--- a/frontend/src/scenes/inbox/components/detail/PullRequestDiffView.tsx
+++ b/frontend/src/scenes/inbox/components/detail/PullRequestDiffView.tsx
@@ -1,4 +1,10 @@
-import { type ChangeTypes, type FileDiffMetadata, type FileDiffOptions, parsePatchFiles } from '@pierre/diffs'
+import {
+ type ChangeTypes,
+ type DiffLineAnnotation,
+ type FileDiffMetadata,
+ type FileDiffOptions,
+ parsePatchFiles,
+} from '@pierre/diffs'
import { FileDiff } from '@pierre/diffs/react'
import { useValues } from 'kea'
import { ReactNode, useEffect, useMemo, useRef, useState } from 'react'
@@ -179,11 +185,21 @@ function FileDiffHeader({ file }: { file: FileDiffMetadata }): JSX.Element {
* commenting. The worker pool is disabled so highlighting runs without a separately-served worker
* bundle; diffs are size-bounded by the backend (see `truncated`), so main-thread is fine.
*/
+/** Whatever the caller anchors to a diff line — inline review threads and the one draft composer. */
+export interface DiffAnnotationData {
+ kind: 'thread' | 'draft'
+ /** Thread key (see `threadKey`) — the caller resolves it back to a thread or draft when rendering. */
+ key: string
+}
+
export function PullRequestDiffView({
diff,
truncated,
cacheKey,
diffStyle = 'unified',
+ annotationsByFile,
+ renderAnnotation,
+ onLineNumberClick,
}: {
diff: string
truncated: boolean
@@ -191,6 +207,12 @@ export function PullRequestDiffView({
cacheKey?: string
/** Unified (stacked) or split (side-by-side) layout, like GitHub's diff view toggle. */
diffStyle?: 'unified' | 'split'
+ /** Inline annotations (review threads, draft composer) keyed by file path. */
+ annotationsByFile?: Record<string, DiffLineAnnotation<DiffAnnotationData>[]>
+ /** Renders one annotation's content below its diff line. */
+ renderAnnotation?: (annotation: DiffLineAnnotation<DiffAnnotationData>) => ReactNode
+ /** Line-number click, GitHub-style "comment on this line". Side: 'RIGHT' = additions, 'LEFT' = deletions. */
+ onLineNumberClick?: (file: string, line: number, side: 'LEFT' | 'RIGHT') => void
}): JSX.Element {
const { isDarkModeOn } = useValues(themeLogic)
@@ -207,16 +229,38 @@ export function PullRequestDiffView({
}
}, [diff, cacheKey])
- const options = useMemo<FileDiffOptions<never>>(
- () => ({
- theme: DIFF_THEME,
- themeType: isDarkModeOn ? 'dark' : 'light',
- diffStyle,
- stickyHeader: true,
- overflow: 'scroll',
- }),
- [isDarkModeOn, diffStyle]
- )
+ // `optionsByFile` exists because Pierre's line events don't carry the file — each file's options
+ // close over its path. The base options are shared; per-file closures are cheap.
+ const optionsByFile = useMemo<Map<string, FileDiffOptions<DiffAnnotationData>>>(() => {
+ const map = new Map<string, FileDiffOptions<DiffAnnotationData>>()
+ for (const file of files) {
+ map.set(file.name, {
+ theme: DIFF_THEME,
+ themeType: isDarkModeOn ? 'dark' : 'light',
+ diffStyle,
+ stickyHeader: true,
+ overflow: 'scroll',
+ ...(onLineNumberClick
+ ? {
+ lineHoverHighlight: 'number' as const,
+ onLineNumberClick: ({
+ lineNumber,
+ annotationSide,
+ }: {
+ lineNumber: number
+ annotationSide: 'additions' | 'deletions'
+ }) =>
+ onLineNumberClick(
+ file.name,
+ lineNumber,
+ annotationSide === 'deletions' ? 'LEFT' : 'RIGHT'
+ ),
+ }
+ : {}),
+ })
+ }
+ return map
+ }, [files, isDarkModeOn, diffStyle, onLineNumberClick])
if (parseFailed) {
return <p className="m-0 text-sm text-danger">Couldn't parse this diff — it may be in an unexpected format.</p>
@@ -232,9 +276,11 @@ export function PullRequestDiffView({
// 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<DiffAnnotationData>
fileDiff={file}
- options={options}
+ options={optionsByFile.get(file.name)}
+ lineAnnotations={annotationsByFile?.[file.name]}
+ renderAnnotation={renderAnnotation}
renderCustomHeader={(fileDiff) => <FileDiffHeader file={fileDiff} />}
disableWorkerPool
/>
diff --git a/frontend/src/scenes/inbox/logics/inboxReportDetailLogic.ts b/frontend/src/scenes/inbox/logics/inboxReportDetailLogic.ts
index e0c1d98192c6..c2fec71a2103 100644
--- a/frontend/src/scenes/inbox/logics/inboxReportDetailLogic.ts
+++ b/frontend/src/scenes/inbox/logics/inboxReportDetailLogic.ts
@@ -2,6 +2,7 @@ import {
MakeLogicType,
actions,
afterMount,
+ connect,
kea,
key,
listeners,
@@ -17,6 +18,7 @@ import { lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
import { SignalNode } from 'scenes/debug/signals/types'
+import { personalIntegrationsLogic } from 'scenes/settings/user/personalIntegrationsLogic'
import { teamLogic } from 'scenes/teamLogic'
import { userLogic } from 'scenes/userLogic'
@@ -25,16 +27,23 @@ import {
signalsReportArtefactsDiff,
signalsReportPrChecks,
signalsReportPrComments,
+ signalsReportPrReviewCommentDestroy,
+ signalsReportPrReviewCommentReactionDestroy,
+ signalsReportPrReviewCommentReactionsCreate,
+ signalsReportPrReviewCommentsCreate,
+ signalsReportPrReviewCommentUpdate,
signalsReportsSignalsRetrieve,
} from 'products/signals/frontend/generated/api'
import type {
CommitDiffResponseApi,
PullRequestCheckApi,
PullRequestCommentApi,
+ PullRequestCommentReactionApi,
ReportChartApi,
} from 'products/signals/frontend/generated/api.schemas'
import type { SignalNodeApi } from '../../../../../products/signals/frontend/generated/api.schemas'
+import type { PersonalGitHubIntegration } from '../../settings/user/personalIntegrationsLogic'
import {
deriveTaskPurpose,
PURPOSE_ORDER,
@@ -102,6 +111,57 @@ export function getTaskPrUrl(task: Task): string | null {
return typeof prUrl === 'string' && prUrl.length > 0 ? prUrl : null
}
+/**
+ * A PR comment plus client-only state layered on top of the generated shape: `pending` marks an
+ * optimistic create/edit still in flight (or failed), so the UI can show it immediately instead of
+ * letting it vanish during the request.
+ */
+export interface ClientPullRequestComment extends PullRequestCommentApi {
+ pending?: 'sending' | 'failed'
+}
+
+/** An inline review-comment thread anchored to a diff line: the root comment plus its replies, in order. */
+export interface ReviewThread {
+ /** Root comment id — the id GitHub reply calls target. */
+ rootId: string
+ path: string
+ /** Anchor line in the diff (the end line for multi-line comments). */
+ line: number
+ /** GitHub diff side: 'RIGHT' = additions, 'LEFT' = deletions. */
+ side: 'LEFT' | 'RIGHT'
+ comments: ClientPullRequestComment[]
+}
+
+/** A not-yet-posted thread the user opened on a diff line. */
+export interface DraftThread {
+ path: string
+ line: number
+ side: 'LEFT' | 'RIGHT'
+}
+
+/** Stable key for a thread or draft anchor, used for posting state and annotation metadata. */
+export function threadKey(anchor: { path: string; line: number; side: string }): string {
+ return `${anchor.path}:${anchor.side}:${anchor.line}`
+}
+
+/** Pull the most specific message out of a review-comment API error, falling back to `fallback`. */
+function reviewCommentError(error: any, fallback: string): string {
+ return error?.data?.error || error?.detail || error?.message || fallback
+}
+
+/**
+ * Replace one comment in `comments`, leaving every other entry untouched. Optimistic updates and their
+ * rollbacks both run against the current list, so a slow request finishing can't undo a delete, edit or
+ * reaction that landed while it was in flight.
+ */
+function patchComment(
+ comments: readonly PullRequestCommentApi[] | null,
+ commentId: string,
+ patch: (comment: ClientPullRequestComment) => ClientPullRequestComment
+): PullRequestCommentApi[] {
+ return (comments ?? []).map((c) => (c.id === commentId ? patch(c) : c))
+}
+
/**
* `explanation` text from the latest judgment artefact of `type`, or null. The priority/actionability
* judgment artefacts already carry the agent's rationale — surfaced in the detail view without any extra fetch.
@@ -121,6 +181,7 @@ function latestJudgmentExplanation(
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface inboxReportDetailLogicValues {
+ personalIntegrations: PersonalGitHubIntegration[] // personalIntegrationsLogic
actionabilityExplanation: string | null
addReviewerOptions: AvailableReviewerOption[]
availableReviewers: AvailableReviewerOption[] | null
@@ -128,19 +189,26 @@ export interface inboxReportDetailLogicValues {
chartIdsKey: string
chartPlacements: ChartPlacements
chartsById: Map<string, ReportChartApi>
+ currentUserGithubLogin: string | null
diffArtefactId: string | null
displayReviewers: EnrichedReviewer[] | null
+ draftThread: DraftThread | null
+ editingCommentId: string | null
expandedTaskIds: string[]
feedbackNoteDraft: string
feedbackNoteOpen: boolean
feedbackNoteSent: boolean
feedbackSentiment: InboxReportFeedbackSentiment | null
hasImplementationPr: boolean
+ hasPersonalGithub: boolean
+ inlineThreadCount: number
+ inlineThreadsByFile: Record<string, ReviewThread[]>
isReResearch: boolean
isReportActive: boolean
isUpdatingReviewers: boolean
latestCommitArtefact: SignalReportArtefact | null
optimisticReviewers: EnrichedReviewer[] | null
+ postingThreadKey: string | null
prChecks: readonly PullRequestCheckApi[] | null
prChecksError: string | null
prChecksLoading: boolean
@@ -169,6 +237,19 @@ export interface inboxReportDetailLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface inboxReportDetailLogicActions {
+ closeDraftThread: () => {
+ value: true
+ }
+ deleteReviewComment: (commentId: string) => {
+ commentId: string
+ }
+ editReviewComment: (
+ commentId: string,
+ body: string
+ ) => {
+ body: string
+ commentId: string
+ }
loadAvailableReviewers: ({ query }?: { query?: string }) => {
query?: string
}
@@ -294,15 +375,42 @@ export interface inboxReportDetailLogicActions {
reportTasks: ReportTaskEntry[]
payload?: any
}
+ openDraftThread: (draft: DraftThread) => {
+ draft: DraftThread
+ }
openFeedbackNote: () => {
value: true
}
+ postReviewComment: (payload: {
+ body: string
+ inReplyTo?: string
+ /** Thread/draft key the composer belongs to, for per-thread posting state. */
+ key: string
+ line?: number
+ path?: string
+ side?: 'LEFT' | 'RIGHT'
+ }) => {
+ payload: {
+ body: string
+ inReplyTo?: string | undefined
+ key: string
+ line?: number | undefined
+ path?: string | undefined
+ side?: 'LEFT' | 'RIGHT' | undefined
+ }
+ }
+ postReviewCommentFinished: () => {
+ value: true
+ }
rateReport: (sentiment: InboxReportFeedbackSentiment) => {
sentiment: InboxReportFeedbackSentiment
}
searchAvailableReviewers: (query: string) => {
query: string
}
+ setEditingCommentId: (commentId: string | null) => {
+ commentId: string | null
+ }
setFeedbackNoteDraft: (draft: string) => {
draft: string
}
@@ -321,6 +429,13 @@ export interface inboxReportDetailLogicActions {
toggleExpandedTask: (taskId: string) => {
taskId: string
}
+ toggleReviewCommentReaction: (
+ commentId: string,
+ content: string
+ ) => {
+ commentId: string
+ content: string
+ }
updateReviewers: (
content: Record<string, string>[],
optimistic: EnrichedReviewer[]
@@ -338,6 +453,10 @@ export interface inboxReportDetailLogicMeta {
reportReviewers: (reportArtefacts: SignalReportArtefact[] | null) => EnrichedReviewer[] | null
isReportActive: (report: SignalReport | null) => boolean
hasImplementationPr: (report: SignalReport | null) => boolean
+ hasPersonalGithub: (personalIntegrations: PersonalGitHubIntegration[]) => boolean
+ currentUserGithubLogin: (personalIntegrations: PersonalGitHubIntegration[]) => string | null
+ inlineThreadsByFile: (prComments: readonly PullRequestCommentApi[] | null) => Record<string, ReviewThread[]>
+ inlineThreadCount: (inlineThreadsByFile: Record<string, ReviewThread[]>) => number
latestCommitArtefact: (reportArtefacts: SignalReportArtefact[] | null) => SignalReportArtefact | null
reportCharts: (report: SignalReport | null) => ReportChartApi[]
chartsById: (reportCharts: ReportChartApi[]) => Map<string, ReportChartApi>
@@ -383,7 +502,33 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([
props({} as InboxReportDetailLogicProps),
key((props) => props.reportId),
+ connect(() => ({
+ // Personal GitHub connection state gates the inline comment composer (comments post as the user).
+ values: [personalIntegrationsLogic, ['integrations as personalIntegrations']],
+ })),
+
actions({
+ // Open a not-yet-posted comment thread on a diff line (one draft at a time).
+ openDraftThread: (draft: DraftThread) => ({ draft }),
+ closeDraftThread: true,
+ // Post an inline review comment: a reply when `inReplyTo` is set, else a new thread on the draft anchor.
+ postReviewComment: (payload: {
+ body: string
+ inReplyTo?: string
+ path?: string
+ line?: number
+ side?: 'LEFT' | 'RIGHT'
+ /** Thread/draft key the composer belongs to, for per-thread posting state. */
+ key: string
+ }) => ({ payload }),
+ postReviewCommentFinished: true,
+ // Edit / delete one of the user's own review comments (optimistic, reverts on failure).
+ editReviewComment: (commentId: string, body: string) => ({ commentId, body }),
+ deleteReviewComment: (commentId: string) => ({ commentId }),
+ // Add or remove the user's own reaction of `content` on a review comment (optimistic toggle).
+ toggleReviewCommentReaction: (commentId: string, content: string) => ({ commentId, content }),
+ // Which comment is being edited inline (null = none).
+ setEditingCommentId: (commentId: string | null) => ({ commentId }),
setReport: (report: SignalReport | null) => ({ report }),
// Optimistically replace the reviewer list while the PUT is in flight, then reload from the server.
// Addressed by report (not artefact) so a report with no reviewers yet can still be assigned one.
@@ -651,6 +796,31 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([
loadPrCommentsFailure: () => "Couldn't load the PR comments from GitHub.",
},
],
+ // The one in-progress draft thread on a diff line. Reset when the report changes.
+ draftThread: [
+ null as DraftThread | null,
+ {
+ openDraftThread: (_, { draft }) => draft,
+ closeDraftThread: () => null,
+ setReport: () => null,
+ },
+ ],
+ // Which thread's composer has a post in flight — gates its submit button and textarea.
+ postingThreadKey: [
+ null as string | null,
+ {
+ postReviewComment: (_, { payload }) => payload.key,
+ postReviewCommentFinished: () => null,
+ },
+ ],
+ // Which comment is open for inline editing. Cleared on a successful edit or when the report changes.
+ editingCommentId: [
+ null as string | null,
+ {
+ setEditingCommentId: (_, { commentId }) => commentId,
+ setReport: () => null,
+ },
+ ],
}),
selectors({
@@ -682,6 +852,64 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([
(s) => [s.report],
(report: SignalReport | null): boolean => !!report?.implementation_pr_url,
],
+ // Whether the current user has a personal GitHub connection — required to post review comments
+ // (they're attributed to the user's own GitHub identity, not the app's).
+ hasPersonalGithub: [
+ (s) => [s.personalIntegrations],
+ (personalIntegrations: PersonalGitHubIntegration[]): boolean => (personalIntegrations ?? []).length > 0,
+ ],
+ // The current user's GitHub login (from their personal connection) — used to attribute optimistic
+ // comments and to tell which comments/reactions are the user's own (editable/removable). Note this
+ // is `github_login`, NOT `account.name` (which is the installation's org/user, e.g. "PostHog").
+ currentUserGithubLogin: [
+ (s) => [s.personalIntegrations],
+ (personalIntegrations: PersonalGitHubIntegration[]): string | null =>
+ personalIntegrations?.[0]?.github_login ?? null,
+ ],
+ // Inline review threads grouped by file path: thread roots (review comments with a line anchor
+ // and no in_reply_to) plus their replies, in chronological order. Outdated comments (null line)
+ // are excluded here — they still show in the Comments section.
+ inlineThreadsByFile: [
+ (s) => [s.prComments],
+ (prComments: readonly PullRequestCommentApi[] | null): Record<string, ReviewThread[]> => {
+ if (!prComments) {
+ return {}
+ }
+ const threads = new Map<string, ReviewThread>()
+ for (const comment of prComments) {
+ if (comment.comment_type !== 'review' || !comment.path || comment.in_reply_to_id) {
+ continue
+ }
+ if (comment.line == null) {
+ continue
+ }
+ threads.set(comment.id, {
+ rootId: comment.id,
+ path: comment.path,
+ line: comment.line,
+ side: comment.side === 'LEFT' ? 'LEFT' : 'RIGHT',
+ comments: [comment],
+ })
+ }
+ for (const comment of prComments) {
+ if (comment.comment_type !== 'review' || !comment.in_reply_to_id) {
+ continue
+ }
+ threads.get(comment.in_reply_to_id)?.comments.push(comment)
+ }
+ const byFile: Record<string, ReviewThread[]> = {}
+ for (const thread of threads.values()) {
+ ;(byFile[thread.path] ??= []).push(thread)
+ }
+ return byFile
+ },
+ ],
+ // Total inline threads, for the Files changed toolbar summary.
+ inlineThreadCount: [
+ (s) => [s.inlineThreadsByFile],
+ (inlineThreadsByFile: Record<string, ReviewThread[]>): number =>
+ Object.values(inlineThreadsByFile).reduce((sum, threads) => sum + threads.length, 0),
+ ],
// 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.
@@ -873,6 +1101,171 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([
actions.setOptimisticReviewers(null)
}
},
+ // Post an inline review comment as the user. The comment is inserted optimistically (marked
+ // `pending: 'sending'`) and the composer/draft closes immediately, so nothing vanishes during
+ // the request. On success the optimistic entry is replaced by the real comment; on failure it's
+ // flagged `pending: 'failed'` (kept visible so the text isn't lost) and a toast explains why.
+ postReviewComment: async ({ payload }) => {
+ const teamId = teamLogic.values.currentTeamId
+ const tempId = `optimistic-${payload.key}-${values.prComments?.length ?? 0}-${payload.body.length}`
+ const login = values.currentUserGithubLogin
+ const optimistic: ClientPullRequestComment = {
+ id: tempId,
+ pending: 'sending',
+ author: login,
+ author_avatar_url: login ? `https://github.com/${login}.png` : null,
+ body: payload.body,
+ created_at: new Date().toISOString(),
+ url: null,
+ comment_type: 'review',
+ path: payload.path ?? null,
+ line: payload.line ?? null,
+ start_line: null,
+ side: payload.side ?? 'RIGHT',
+ diff_hunk: null,
+ in_reply_to_id: payload.inReplyTo ?? null,
+ commit_id: null,
+ reactions: [],
+ }
+ actions.loadPrCommentsSuccess([...(values.prComments ?? []), optimistic])
+ actions.closeDraftThread()
+ try {
+ const response = await signalsReportPrReviewCommentsCreate(String(teamId), props.reportId, {
+ body: payload.body,
+ in_reply_to: payload.inReplyTo ?? null,
+ path: payload.path ?? null,
+ line: payload.line ?? null,
+ side: payload.side ?? null,
+ })
+ actions.loadPrCommentsSuccess(
+ (values.prComments ?? []).map((c) => (c.id === tempId ? response.comment : c))
+ )
+ } catch (error: any) {
+ actions.loadPrCommentsSuccess(
+ (values.prComments ?? []).map((c) =>
+ c.id === tempId ? { ...(c as ClientPullRequestComment), pending: 'failed' } : c
+ )
+ )
+ lemonToast.error(reviewCommentError(error, "Couldn't post the comment to GitHub"))
+ } finally {
+ actions.postReviewCommentFinished()
+ }
+ },
+ // Edit one of the user's own review comments. Optimistically swaps the body in; a failure puts
+ // back only that comment's body.
+ editReviewComment: async ({ commentId, body }) => {
+ const teamId = teamLogic.values.currentTeamId
+ const previous = (values.prComments ?? []).find((c) => c.id === commentId)
+ actions.setEditingCommentId(null)
+ if (!teamId || !previous) {
+ return
+ }
+ actions.loadPrCommentsSuccess(
+ patchComment(values.prComments, commentId, (c) => ({ ...c, body, pending: 'sending' }))
+ )
+ try {
+ const response = await signalsReportPrReviewCommentUpdate(String(teamId), props.reportId, commentId, {
+ body,
+ })
+ actions.loadPrCommentsSuccess(patchComment(values.prComments, commentId, () => response.comment))
+ } catch (error: any) {
+ actions.loadPrCommentsSuccess(
+ patchComment(values.prComments, commentId, (c) => ({
+ ...c,
+ body: previous.body,
+ pending: undefined,
+ }))
+ )
+ lemonToast.error(reviewCommentError(error, "Couldn't save the edit"))
+ }
+ },
+ // Delete one of the user's own review comments. Optimistically removes it; a failure slots it
+ // back at its old index in the list as it stands now.
+ deleteReviewComment: async ({ commentId }) => {
+ const teamId = teamLogic.values.currentTeamId
+ const index = (values.prComments ?? []).findIndex((c) => c.id === commentId)
+ if (!teamId || index === -1) {
+ return
+ }
+ const removed = (values.prComments ?? [])[index]
+ actions.loadPrCommentsSuccess((values.prComments ?? []).filter((c) => c.id !== commentId))
+ try {
+ await signalsReportPrReviewCommentDestroy(String(teamId), props.reportId, commentId)
+ } catch (error: any) {
+ const current = (values.prComments ?? []).filter((c) => c.id !== commentId)
+ actions.loadPrCommentsSuccess([...current.slice(0, index), removed, ...current.slice(index)])
+ lemonToast.error(reviewCommentError(error, "Couldn't delete the comment"))
+ }
+ },
+ // Toggle the user's own reaction of `content` on a comment. Optimistically adds/removes the
+ // reaction, then confirms with the server (add returns the real reaction id). A failure puts back
+ // only that one reaction, so a reaction toggled concurrently on the same comment isn't clobbered.
+ toggleReviewCommentReaction: async ({ commentId, content }) => {
+ const teamId = teamLogic.values.currentTeamId
+ const login = values.currentUserGithubLogin
+ if (!teamId || !login) {
+ return
+ }
+ const comment = (values.prComments ?? []).find((c) => c.id === commentId)
+ const mine = comment?.reactions?.find((r) => r.content === content && r.user_login === login)
+
+ if (mine) {
+ actions.loadPrCommentsSuccess(
+ patchComment(values.prComments, commentId, (c) => ({
+ ...c,
+ reactions: (c.reactions ?? []).filter((r) => r.id !== mine.id),
+ }))
+ )
+ try {
+ await signalsReportPrReviewCommentReactionDestroy(
+ String(teamId),
+ props.reportId,
+ commentId,
+ mine.id
+ )
+ } catch (error: any) {
+ actions.loadPrCommentsSuccess(
+ patchComment(values.prComments, commentId, (c) => ({
+ ...c,
+ reactions: [...(c.reactions ?? []).filter((r) => r.id !== mine.id), mine],
+ }))
+ )
+ lemonToast.error(reviewCommentError(error, "Couldn't remove the reaction"))
+ }
+ return
+ }
+
+ const tempId = `optimistic-rx-${commentId}-${content}`
+ const optimisticReaction: PullRequestCommentReactionApi = { id: tempId, content, user_login: login }
+ actions.loadPrCommentsSuccess(
+ patchComment(values.prComments, commentId, (c) => ({
+ ...c,
+ reactions: [...(c.reactions ?? []), optimisticReaction],
+ }))
+ )
+ try {
+ const response = await signalsReportPrReviewCommentReactionsCreate(
+ String(teamId),
+ props.reportId,
+ commentId,
+ { content: content as any }
+ )
+ actions.loadPrCommentsSuccess(
+ patchComment(values.prComments, commentId, (c) => ({
+ ...c,
+ reactions: (c.reactions ?? []).map((r) => (r.id === tempId ? response.reaction : r)),
+ }))
+ )
+ } catch (error: any) {
+ actions.loadPrCommentsSuccess(
+ patchComment(values.prComments, commentId, (c) => ({
+ ...c,
+ reactions: (c.reactions ?? []).filter((r) => r.id !== tempId),
+ }))
+ )
+ lemonToast.error(reviewCommentError(error, "Couldn't add the reaction"))
+ }
+ },
// The artefact log is the single source for the activity timeline AND the task associations,
// so deriving the linked tasks hangs off each successful artefact load rather than issuing a
// second identical fetch. The branch diff also cascades from here (once artefacts resolve we
diff --git a/frontend/src/scenes/settings/user/personalIntegrationsLogic.ts b/frontend/src/scenes/settings/user/personalIntegrationsLogic.ts
index 087277725af8..0a60a21fe821 100644
--- a/frontend/src/scenes/settings/user/personalIntegrationsLogic.ts
+++ b/frontend/src/scenes/settings/user/personalIntegrationsLogic.ts
@@ -26,6 +26,8 @@ export interface PersonalGitHubIntegration {
installation_id: string | null
repository_selection: string | null
account: { type: string; name: string } | null
+ /** The connected user's own GitHub login (distinct from `account`, which is the installation org/user). */
+ github_login: string | null
uses_shared_installation: boolean
created_at: string | null
}
diff --git a/posthog/api/user_integration.py b/posthog/api/user_integration.py
index c16931ff4dc8..112acc724408 100644
--- a/posthog/api/user_integration.py
+++ b/posthog/api/user_integration.py
@@ -86,6 +86,11 @@ class UserGitHubIntegrationItemSerializer(serializers.Serializer):
allow_null=True,
help_text="Installation account metadata from GitHub.",
)
+ github_login = serializers.CharField(
+ required=False,
+ allow_null=True,
+ help_text="The connected user's own GitHub login (distinct from the installation account).",
+ )
uses_shared_installation = serializers.BooleanField(
help_text="True when this installation id matches a team-level GitHub integration on the active project.",
)
@@ -792,6 +797,9 @@ def _serialize_github_integration(
"installation_id": integration.integration_id,
"repository_selection": integration.config.get("repository_selection"),
"account": integration.config.get("account"),
+ # The user's own GitHub login (distinct from `account`, which is the installation's
+ # org/user). Lets the frontend tell which PR comments/reactions are the user's own.
+ "github_login": (integration.config.get("github_user") or {}).get("login"),
"uses_shared_installation": integration.integration_id in team_integration_installation_ids,
"created_at": integration.created_at,
}
diff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.py
index 91250903c1da..e059676acd8b 100644
--- a/posthog/models/github_integration_base.py
+++ b/posthog/models/github_integration_base.py
@@ -47,6 +47,11 @@ GITHUB_BRANCH_CACHE_TIMEOUT_SECONDS = 60 * 60 * 24
INSTALLATION_UNAVAILABLE_SINCE_CONFIG_KEY = "installation_unavailable_since"
+# Reactions cost one extra round trip per reacted comment, and GitHub offers no way to fetch them in
+# bulk, so bound the fan-out. Set high enough that a real pull request never reaches it: past this
+# point a comment renders without its pills, which is worse than the extra requests.
+MAX_REACTION_HYDRATIONS = 100
+
class NormalizedPRComment(TypedDict):
"""Wire shape for a PR comment shared by the read path and the review-comment write endpoints."""
@@ -66,6 +71,7 @@ class NormalizedPRComment(TypedDict):
diff_hunk: str | None
in_reply_to_id: str | None
commit_id: str | None
+ reactions: list[dict[str, Any]]
@dataclass(frozen=True)
@@ -1077,7 +1083,8 @@ class GitHubIntegrationBase:
@staticmethod
def normalize_pr_comment(raw: object, comment_type: str) -> NormalizedPRComment | None:
- """Shape a raw GitHub comment into the wire contract."""
+ """Shape a raw GitHub comment into the wire contract shared by the read path and the write
+ endpoints. ``reactions`` is left empty; the read path fills it for review comments that have any."""
if not isinstance(raw, dict):
return None
user = raw.get("user") or {}
@@ -1100,6 +1107,7 @@ class GitHubIntegrationBase:
"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,
+ "reactions": [],
}
def get_pull_request_comments(self, repository: str, pr_number: int) -> dict[str, Any]:
@@ -1112,6 +1120,7 @@ class GitHubIntegrationBase:
repo_path = repository if "/" in repository else f"{self.organization()}/{repository}"
comments: list[NormalizedPRComment] = []
+ hydrated_reactions = 0
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"),
@@ -1137,12 +1146,53 @@ class GitHubIntegrationBase:
normalized = self.normalize_pr_comment(raw, comment_type)
if normalized is None:
continue
+ if comment_type == "review" and hydrated_reactions < MAX_REACTION_HYDRATIONS:
+ reaction_summary = raw.get("reactions") or {}
+ if isinstance(reaction_summary, dict) and reaction_summary.get("total_count"):
+ normalized["reactions"] = self._get_review_comment_reactions(repo_path, str(raw["id"]))
+ hydrated_reactions += 1
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 _get_review_comment_reactions(self, repo_path: str, comment_id: str) -> list[dict[str, Any]]:
+ """Fetch a review comment's reactions, each with its id, content, and reactor login.
+
+ Returned per-reactor (not just counts) so the frontend can group them, highlight the viewer's
+ own, and delete them by id. Best-effort: returns [] on any non-200 / parse failure.
+ """
+ try:
+ # One page only: a comment past 100 reactions isn't worth extra round trips here.
+ response = self._installation_authenticated_get(
+ f"https://api.github.com/repos/{repo_path}/pulls/comments/{comment_id}/reactions",
+ endpoint="/repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions",
+ params={"per_page": 100},
+ )
+ except Exception:
+ logger.warning("GitHubIntegration: reactions fetch failed", repository=repo_path, comment_id=comment_id)
+ return []
+ if response is None or response.status_code != 200:
+ return []
+ try:
+ body = response.json()
+ except Exception:
+ return []
+ if not isinstance(body, list):
+ return []
+ out: list[dict[str, Any]] = []
+ for reaction in body:
+ if isinstance(reaction, dict) and reaction.get("content") and reaction.get("id") is not None:
+ out.append(
+ {
+ "id": str(reaction["id"]),
+ "content": reaction["content"],
+ "user_login": (reaction.get("user") or {}).get("login"),
+ }
+ )
+ return out
+
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/user_integration.py b/posthog/models/user_integration.py
index 5aed60bcad26..42450a202e38 100644
--- a/posthog/models/user_integration.py
+++ b/posthog/models/user_integration.py
@@ -8,6 +8,7 @@ from django.db import models
import requests
import structlog
+from posthog.egress.github.transport import github_request, raise_if_github_rate_limited
from posthog.egress.limiter.policies import Priority
from posthog.helpers.encrypted_fields import EncryptedJSONField
from posthog.models.github_integration_base import GitHubIntegrationBase
@@ -283,6 +284,169 @@ class UserGitHubIntegration(GitHubIntegrationBase):
assert token is not None, "user_access_token cleared unexpectedly after refresh"
return token
+ def create_pull_request_review_comment(
+ self,
+ repository: str,
+ pr_number: int,
+ body: str,
+ *,
+ in_reply_to: str | None = None,
+ commit_id: str | None = None,
+ path: str | None = None,
+ line: int | None = None,
+ side: str | None = None,
+ ) -> dict[str, Any]:
+ """Post an inline PR review comment as the user (user-to-server token).
+
+ Two shapes, matching GitHub's API: a reply to an existing thread needs only
+ ``in_reply_to`` (the thread root comment id); a new thread needs ``commit_id``
+ (the PR head SHA) + ``path`` + ``line`` (+ ``side``). The comment is attributed
+ to the user's GitHub identity, not the app.
+
+ Raises :class:`ReauthorizationRequired` when the stored user token is unusable
+ and :class:`GitHubRateLimitError` on rate limits; other failures return
+ ``{"success": False, "error": ...}``.
+ """
+ token = self.get_usable_user_access_token()
+ repo_path = repository if "/" in repository else f"{self.organization()}/{repository}"
+
+ payload: dict[str, Any]
+ if in_reply_to is not None:
+ url = f"https://api.github.com/repos/{repo_path}/pulls/{pr_number}/comments/{in_reply_to}/replies"
+ endpoint = "/repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies"
+ payload = {"body": body}
+ else:
+ if not (commit_id and path and line):
+ return {"success": False, "error": "New comment threads need commit_id, path, and line"}
+ url = f"https://api.github.com/repos/{repo_path}/pulls/{pr_number}/comments"
+ endpoint = "/repos/{owner}/{repo}/pulls/{pull_number}/comments"
+ payload = {"body": body, "commit_id": commit_id, "path": path, "line": line, "side": side or "RIGHT"}
+
+ response = github_request(
+ "POST",
+ url,
+ source="signals_pr_review_comment",
+ headers={"Authorization": f"Bearer {token}", "Accept": "application/vnd.github+json"},
+ installation_id=self.github_installation_id,
+ priority=Priority.CRITICAL,
+ endpoint=endpoint,
+ json=payload,
+ timeout=15,
+ )
+ raise_if_github_rate_limited(response)
+ if response.status_code not in (200, 201):
+ logger.warning(
+ "UserGitHubIntegration: review comment post failed",
+ status_code=response.status_code,
+ repository=repo_path,
+ pr_number=pr_number,
+ )
+ return {
+ "success": False,
+ "error": f"GitHub rejected the comment (HTTP {response.status_code})",
+ "status_code": response.status_code,
+ }
+ return {"success": True, "comment": response.json()}
+
+ def _user_review_comment_request(
+ self,
+ method: str,
+ repository: str,
+ path_suffix: str,
+ *,
+ source: str,
+ json: dict[str, Any] | None = None,
+ ) -> dict[str, Any]:
+ """Shared transport for user-authored reads and edits of a review comment (fetch/edit/delete/react).
+
+ ``path_suffix`` is appended to ``/repos/{repo}/pulls/comments`` — e.g. ``/{id}`` for a
+ comment or ``/{id}/reactions`` for its reactions. Returns ``{"success", ...}``; raises
+ :class:`ReauthorizationRequired`/:class:`GitHubRateLimitError` like the create path.
+ """
+ token = self.get_usable_user_access_token()
+ repo_path = repository if "/" in repository else f"{self.organization()}/{repository}"
+ response = github_request(
+ method,
+ f"https://api.github.com/repos/{repo_path}/pulls/comments{path_suffix}",
+ source=source,
+ headers={"Authorization": f"Bearer {token}", "Accept": "application/vnd.github+json"},
+ installation_id=self.github_installation_id,
+ priority=Priority.CRITICAL,
+ json=json,
+ timeout=15,
+ )
+ raise_if_github_rate_limited(response)
+ if response.status_code not in (200, 201, 204):
+ logger.warning(
+ "UserGitHubIntegration: review comment request failed",
+ method=method,
+ status_code=response.status_code,
+ repository=repo_path,
+ )
+ return {
+ "success": False,
+ "error": f"GitHub rejected the change (HTTP {response.status_code})",
+ "status_code": response.status_code,
+ }
+ body = response.json() if response.status_code != 204 and response.content else None
+ return {"success": True, "result": body}
+
+ def get_pull_request_review_comment(self, repository: str, comment_id: str) -> dict[str, Any]:
+ """Fetch a single review comment as the user, so callers can check what it hangs off before
+ writing to it. ``comment`` is None when GitHub says there is no such comment this user can
+ see, which callers should treat the same as a comment that isn't theirs to touch.
+ """
+ result = self._user_review_comment_request(
+ "GET", repository, f"/{comment_id}", source="signals_pr_review_comment_fetch"
+ )
+ if result.get("success"):
+ return {"success": True, "comment": result.get("result")}
+ if result.get("status_code") == 404:
+ return {"success": True, "comment": None}
+ return result
+
+ def update_pull_request_review_comment(self, repository: str, comment_id: str, body: str) -> dict[str, Any]:
+ """Edit an existing review comment's body as the user."""
+ result = self._user_review_comment_request(
+ "PATCH", repository, f"/{comment_id}", source="signals_pr_review_comment_edit", json={"body": body}
+ )
+ if result.get("success"):
+ return {"success": True, "comment": result.get("result")}
+ return result
+
+ def delete_pull_request_review_comment(self, repository: str, comment_id: str) -> dict[str, Any]:
+ """Delete a review comment as the user."""
+ return self._user_review_comment_request(
+ "DELETE", repository, f"/{comment_id}", source="signals_pr_review_comment_delete"
+ )
+
+ def add_pull_request_review_comment_reaction(
+ self, repository: str, comment_id: str, content: str
+ ) -> dict[str, Any]:
+ """Add an emoji reaction to a review comment as the user. ``content`` is a GitHub reaction
+ key (``+1``, ``-1``, ``laugh``, ``hooray``, ``confused``, ``heart``, ``rocket``, ``eyes``)."""
+ result = self._user_review_comment_request(
+ "POST",
+ repository,
+ f"/{comment_id}/reactions",
+ source="signals_pr_review_comment_reaction",
+ json={"content": content},
+ )
+ if result.get("success"):
+ return {"success": True, "reaction": result.get("result")}
+ return result
+
+ def delete_pull_request_review_comment_reaction(
+ self, repository: str, comment_id: str, reaction_id: str
+ ) -> dict[str, Any]:
+ """Remove one of the user's own reactions from a review comment."""
+ return self._user_review_comment_request(
+ "DELETE",
+ repository,
+ f"/{comment_id}/reactions/{reaction_id}",
+ source="signals_pr_review_comment_reaction_delete",
+ )
+
def _apply_user_token_payload(self, payload: dict[str, Any]) -> None:
"""Write a fresh user token pair + expirations onto the integration row."""
now = int(time.time())
diff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.py
index 8eb848aba282..015224fe5c28 100644
--- a/products/signals/backend/serializers.py
+++ b/products/signals/backend/serializers.py
@@ -962,6 +962,19 @@ class PullRequestChecksResponseSerializer(serializers.Serializer):
checks = PullRequestCheckSerializer(many=True, read_only=True)
+class PullRequestCommentReactionSerializer(serializers.Serializer):
+ """One emoji reaction on a review comment, with the reactor so the viewer's own can be toggled."""
+
+ id = serializers.CharField(read_only=True, help_text="GitHub reaction id (needed to remove it).")
+ content = serializers.CharField(
+ read_only=True,
+ help_text="Reaction key: '+1', '-1', 'laugh', 'hooray', 'confused', 'heart', 'rocket', or 'eyes'.",
+ )
+ user_login = serializers.CharField(
+ read_only=True, allow_null=True, help_text="GitHub login of the user who added the reaction."
+ )
+
+
class PullRequestCommentSerializer(serializers.Serializer):
"""One comment on a pull request — a conversation comment or an inline review comment."""
@@ -1012,9 +1025,83 @@ class PullRequestCommentSerializer(serializers.Serializer):
allow_null=True,
help_text="SHA of the commit the review comment was made against (review comments only).",
)
+ reactions = PullRequestCommentReactionSerializer(
+ many=True,
+ read_only=True,
+ help_text="Emoji reactions on this review comment, one entry per reactor.",
+ )
class PullRequestCommentsResponseSerializer(serializers.Serializer):
"""Response for the PR comments endpoint — conversation and review comments merged chronologically."""
comments = PullRequestCommentSerializer(many=True, read_only=True)
+
+
+class PullRequestReviewCommentCreateSerializer(serializers.Serializer):
+ """Request body for posting an inline PR review comment as the requesting user.
+
+ Two shapes: a reply to an existing thread (only `body` + `in_reply_to`), or a new
+ thread on a diff line (`body` + `path` + `line`, optionally `side`)."""
+
+ body = serializers.CharField(help_text="Comment body (GitHub-flavored markdown).", max_length=65536)
+ # Numeric-only: this id is interpolated into the GitHub reply URL, so an unconstrained string could
+ # smuggle path segments (e.g. `../../issues/1/comments`) and retarget the request.
+ in_reply_to = serializers.RegexField(
+ r"^[0-9]+$",
+ required=False,
+ allow_null=True,
+ help_text="Numeric id of the thread root comment to reply to. When set, path/line/side are ignored.",
+ )
+ path = serializers.CharField(
+ required=False,
+ allow_null=True,
+ help_text="File path to anchor a new comment thread to (required when starting a new thread).",
+ )
+ line = serializers.IntegerField(
+ required=False,
+ allow_null=True,
+ min_value=1,
+ help_text="Diff line to anchor a new comment thread to (required when starting a new thread).",
+ )
+ side = serializers.ChoiceField(
+ required=False,
+ allow_null=True,
+ choices=["LEFT", "RIGHT"],
+ help_text="Diff side of the anchor line: 'LEFT' = deletions, 'RIGHT' = additions. Defaults to 'RIGHT'.",
+ )
+
+ def validate(self, attrs: dict) -> dict:
+ if not attrs.get("in_reply_to") and not (attrs.get("path") and attrs.get("line")):
+ raise serializers.ValidationError("Provide either in_reply_to (reply) or path + line (new thread).")
+ return attrs
+
+
+class PullRequestReviewCommentCreateResponseSerializer(serializers.Serializer):
+ """Response after posting a review comment — the created comment in the normalized PR-comment shape."""
+
+ comment = PullRequestCommentSerializer(read_only=True)
+
+
+class PullRequestReviewCommentUpdateSerializer(serializers.Serializer):
+ """Request body for editing a review comment's markdown body."""
+
+ body = serializers.CharField(help_text="New comment body (GitHub-flavored markdown).", max_length=65536)
+
+
+_REACTION_CONTENTS = ["+1", "-1", "laugh", "hooray", "confused", "heart", "rocket", "eyes"]
+
+
+class PullRequestReviewCommentReactionCreateSerializer(serializers.Serializer):
+ """Request body for adding an emoji reaction to a review comment."""
+
+ content = serializers.ChoiceField(
+ choices=_REACTION_CONTENTS,
+ help_text="Reaction to add: one of '+1', '-1', 'laugh', 'hooray', 'confused', 'heart', 'rocket', 'eyes'.",
+ )
+
+
+class PullRequestReviewCommentReactionCreateResponseSerializer(serializers.Serializer):
+ """Response after adding a reaction — the created reaction, so the frontend can track its id."""
+
+ reaction = PullRequestCommentReactionSerializer(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 8a56493d18d0..b2118d3f4a58 100644
--- a/products/signals/backend/test/test_signal_report_api.py
+++ b/products/signals/backend/test/test_signal_report_api.py
@@ -20,7 +20,15 @@ from social_django.models import UserSocialAuth
from posthog.egress.github.transport import GitHubEgressBudgetExhausted
from posthog.egress.limiter.policies import Priority
+from posthog.models import OAuthApplication
from posthog.models.team.team import Team
+from posthog.models.user_integration import UserIntegration
+from posthog.temporal.oauth import (
+ ARRAY_APP_CLIENT_ID_DEV,
+ ARRAY_APP_CLIENT_ID_EU,
+ ARRAY_APP_CLIENT_ID_US,
+ create_oauth_access_token_for_user,
+)
from products.signals.backend.implementation_pr import (
fetch_implementation_pr_state_for_reports,
@@ -34,6 +42,23 @@ if TYPE_CHECKING:
from products.tasks.backend.models import Task, TaskRun
+def authenticate_as_sandbox_token(test: APIBaseTest) -> None:
+ for client_id in (ARRAY_APP_CLIENT_ID_DEV, ARRAY_APP_CLIENT_ID_US, ARRAY_APP_CLIENT_ID_EU):
+ OAuthApplication.objects.get_or_create(
+ client_id=client_id,
+ defaults={
+ "name": "Array Test App",
+ "client_type": OAuthApplication.CLIENT_PUBLIC,
+ "authorization_grant_type": OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ "redirect_uris": "https://app.posthog.com/callback",
+ "algorithm": "RS256",
+ },
+ )
+ token = create_oauth_access_token_for_user(test.user, test.team.id, scopes=["task:read", "task:write"])
+ test.client.logout()
+ test.client.credentials(HTTP_AUTHORIZATION=f"Bearer {token}")
+
+
class TestSignalReportDeleteAPI(APIBaseTest):
def _url(self, report_id: str | None = None) -> str:
base = f"/api/projects/{self.team.id}/signals/reports/"
@@ -2344,6 +2369,100 @@ class TestSignalReportPrEndpoints(APIBaseTest):
def _comments_url(self, report_id: str) -> str:
return f"/api/projects/{self.team.id}/signals/reports/{report_id}/pr_comments/"
+ def _review_comment_url(self, report_id: str, comment_id: str) -> str:
+ return f"/api/projects/{self.team.id}/signals/reports/{report_id}/pr_review_comments/{comment_id}/"
+
+ @parameterized.expand(
+ [
+ ("edit_other_pr", "patch", "", {"body": "edited"}, "8", status.HTTP_404_NOT_FOUND),
+ ("delete_other_pr", "delete", "", None, "8", status.HTTP_404_NOT_FOUND),
+ ("react_other_pr", "post", "reactions/", {"content": "+1"}, "8", status.HTTP_404_NOT_FOUND),
+ ("unreact_other_pr", "delete", "reactions/5/", None, "8", status.HTTP_404_NOT_FOUND),
+ ("delete_own_pr", "delete", "", None, "7", status.HTTP_204_NO_CONTENT),
+ ]
+ )
+ def test_review_comment_writes_are_scoped_to_the_reports_pr(
+ self, _name, method, suffix, payload, comment_pr, expected_status
+ ):
+ report = self._create_report()
+ UserIntegration.objects.create(user=self.user, kind=UserIntegration.IntegrationKind.GITHUB, integration_id="42")
+ user_github = patch("products.signals.backend.views.UserGitHubIntegration").start()
+ self.addCleanup(patch.stopall)
+ user_github.return_value.get_pull_request_review_comment.return_value = {
+ "success": True,
+ "comment": {
+ "id": 99,
+ "pull_request_url": f"https://api.github.com/repos/PostHog/posthog/pulls/{comment_pr}",
+ },
+ }
+ user_github.return_value.delete_pull_request_review_comment.return_value = {"success": True}
+ 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 = getattr(self.client, method)(
+ self._review_comment_url(str(report.id), "99") + suffix, data=payload, format="json"
+ )
+ assert response.status_code == expected_status
+
+ @parameterized.expand(
+ [
+ ("create", "post", "", {"body": "hi", "in_reply_to": "1"}),
+ ("edit", "patch", "99/", {"body": "edited"}),
+ ("delete", "delete", "99/", None),
+ ("react", "post", "99/reactions/", {"content": "+1"}),
+ ("unreact", "delete", "99/reactions/5/", None),
+ ]
+ )
+ def test_sandbox_oauth_token_cannot_write_review_comments_as_the_user(self, _name, method, suffix, payload):
+ # These writes reach GitHub under the requesting human's personal connection. A sandbox/agent
+ # token is minted as the task actor and carries task:write, so without the guard a prompt-injected
+ # run could comment, edit, delete, or react as the person who started it.
+ report = self._create_report()
+ UserIntegration.objects.create(user=self.user, kind=UserIntegration.IntegrationKind.GITHUB, integration_id="42")
+ user_github = patch("products.signals.backend.views.UserGitHubIntegration").start()
+ self.addCleanup(patch.stopall)
+ authenticate_as_sandbox_token(self)
+
+ 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 = getattr(self.client, method)(
+ f"/api/projects/{self.team.id}/signals/reports/{report.id}/pr_review_comments/{suffix}",
+ data=payload,
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ user_github.assert_not_called()
+
+ def test_personal_api_key_cannot_write_review_comments_as_the_user(self):
+ # A personal API key is issued to automate against the API, not to act as its owner on
+ # GitHub. Only a browser session is admitted, so holding task:write must not be enough to
+ # reach the user's linked GitHub account. One endpoint is enough: every write resolves the
+ # caller through the same guard.
+ report = self._create_report()
+ UserIntegration.objects.create(user=self.user, kind=UserIntegration.IntegrationKind.GITHUB, integration_id="42")
+ user_github = patch("products.signals.backend.views.UserGitHubIntegration").start()
+ self.addCleanup(patch.stopall)
+ key_value = self.create_personal_api_key_with_scopes(["task:read", "task:write"])
+ self.client.logout()
+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {key_value}")
+
+ 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.post(
+ f"/api/projects/{self.team.id}/signals/reports/{report.id}/pr_review_comments/",
+ data={"body": "hi", "in_reply_to": "1"},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ user_github.assert_not_called()
+
def test_pr_checks_404_when_report_has_no_implementation_pr(self):
report = self._create_report()
with patch(
diff --git a/products/signals/backend/views.py b/products/signals/backend/views.py
index 8cc3ba09565f..7c3dcb32d6ba 100644
--- a/products/signals/backend/views.py
+++ b/products/signals/backend/views.py
@@ -1,6 +1,6 @@
import json
import uuid
-from collections.abc import Sequence
+from collections.abc import Callable, Sequence
from datetime import UTC, timedelta
from typing import Any, cast
@@ -56,8 +56,10 @@ from posthog.exceptions_capture import capture_exception
from posthog.models import Team, User
from posthog.models.activity_logging.activity_log import Change, Detail, log_activity
from posthog.models.activity_logging.model_activity import is_impersonated_session
+from posthog.models.github_integration_base import GitHubIntegrationBase
from posthog.models.integration import GitHubIntegration, Integration
from posthog.models.team.extensions import get_or_create_team_extension
+from posthog.models.user_integration import ReauthorizationRequired, UserGitHubIntegration, UserIntegration
from posthog.permissions import APIScopePermission
from posthog.temporal.common.client import sync_connect
from posthog.user_permissions import UserPermissions
@@ -112,6 +114,11 @@ from products.signals.backend.serializers import (
CommitDiffResponseSerializer,
PullRequestChecksResponseSerializer,
PullRequestCommentsResponseSerializer,
+ PullRequestReviewCommentCreateResponseSerializer,
+ PullRequestReviewCommentCreateSerializer,
+ PullRequestReviewCommentReactionCreateResponseSerializer,
+ PullRequestReviewCommentReactionCreateSerializer,
+ PullRequestReviewCommentUpdateSerializer,
ReportSignalsResponseSerializer,
SignalReportArtefactLogCreateSerializer,
SignalReportArtefactLogUpdateSerializer,
@@ -2242,6 +2249,349 @@ class SignalReportViewSet(
cast(SignalReport, self.get_object()), "get_pull_request_comments", "comments", "comments"
)
+ @extend_schema(
+ request=PullRequestReviewCommentCreateSerializer,
+ responses={
+ 201: OpenApiResponse(
+ response=PullRequestReviewCommentCreateResponseSerializer,
+ description="The created review comment, in the normalized PR-comment shape.",
+ ),
+ 400: OpenApiResponse(description="Invalid comment payload."),
+ 403: OpenApiResponse(
+ description="Not a signed-in user, or the requesting user has no usable personal GitHub "
+ "connection (reconnect GitHub)."
+ ),
+ 404: OpenApiResponse(
+ description="Report has no implementation PR, or no GitHub integration can access it."
+ ),
+ 502: OpenApiResponse(description="GitHub rejected the comment."),
+ 503: OpenApiResponse(description="The GitHub egress budget is temporarily unavailable."),
+ },
+ summary="Post an inline review comment on a report's implementation PR",
+ description=(
+ "Post an inline review comment on the report's implementation pull request, attributed to the "
+ "requesting user's own GitHub identity via their personal GitHub connection. Either replies to "
+ "an existing thread (`in_reply_to`) or starts a new thread on a diff line (`path` + `line`)."
+ ),
+ operation_id="signals_report_pr_review_comments_create",
+ )
+ @action(detail=True, methods=["post"], url_path="pr_review_comments", required_scopes=["task:write"])
+ def pr_review_comments(self, request: Request, *args, **kwargs) -> Response:
+ report = cast(SignalReport, self.get_object())
+ serializer = PullRequestReviewCommentCreateSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ params = serializer.validated_data
+
+ resolved = self._resolve_user_github_and_pr(report, request)
+ if isinstance(resolved, Response):
+ return resolved
+ user_github, repository, pr_number = resolved
+
+ commit_id: str | None = None
+ if not params.get("in_reply_to"):
+ # New threads anchor to the PR head commit; resolve it via the team integration
+ # (read path), so the user token is only used for the write itself.
+ github, repository, pr_number, error = self._github_for_report_pr(report, reference=(repository, pr_number))
+ if error is not None:
+ return error
+ assert github is not None
+ pr_details = github.get_pull_request(repository, pr_number)
+ commit_id = pr_details.get("head_sha") if pr_details.get("success") else None
+ if not commit_id:
+ return Response(
+ {"error": "Could not resolve the pull request's head commit."},
+ status=status.HTTP_502_BAD_GATEWAY,
+ )
+
+ result = self._run_user_github_write(
+ lambda: user_github.create_pull_request_review_comment(
+ repository,
+ pr_number,
+ params["body"],
+ in_reply_to=params.get("in_reply_to"),
+ commit_id=commit_id,
+ path=params.get("path"),
+ line=params.get("line"),
+ side=params.get("side"),
+ ),
+ repository,
+ pr_number,
+ noun="comment",
+ )
+ if isinstance(result, Response):
+ return result
+
+ self._bust_pr_comments_cache(repository, pr_number)
+ return self._pr_review_comment_response(result["comment"], status_code=status.HTTP_201_CREATED)
+
+ @extend_schema(
+ methods=["PATCH"],
+ parameters=[OpenApiParameter("comment_id", OpenApiTypes.STR, OpenApiParameter.PATH)],
+ request=PullRequestReviewCommentUpdateSerializer,
+ responses={
+ 200: OpenApiResponse(
+ response=PullRequestReviewCommentCreateResponseSerializer,
+ description="The edited review comment, in the normalized PR-comment shape.",
+ ),
+ 403: OpenApiResponse(
+ description="Not a signed-in user, no usable personal GitHub connection, or not the comment's author."
+ ),
+ 404: OpenApiResponse(description="Report has no implementation PR, or the comment isn't on it."),
+ 502: OpenApiResponse(description="GitHub rejected the edit."),
+ 503: OpenApiResponse(description="The GitHub egress budget is temporarily unavailable."),
+ },
+ summary="Edit one of the requesting user's own review comments",
+ operation_id="signals_report_pr_review_comment_update",
+ )
+ @extend_schema(
+ methods=["DELETE"],
+ parameters=[OpenApiParameter("comment_id", OpenApiTypes.STR, OpenApiParameter.PATH)],
+ responses={
+ 204: OpenApiResponse(description="Comment deleted."),
+ 403: OpenApiResponse(
+ description="Not a signed-in user, no usable personal GitHub connection, or not the comment's author."
+ ),
+ 404: OpenApiResponse(description="Report has no implementation PR, or the comment isn't on it."),
+ 502: OpenApiResponse(description="GitHub rejected the delete."),
+ 503: OpenApiResponse(description="The GitHub egress budget is temporarily unavailable."),
+ },
+ summary="Delete one of the requesting user's own review comments",
+ operation_id="signals_report_pr_review_comment_destroy",
+ )
+ @action(
+ detail=True,
+ methods=["patch", "delete"],
+ url_path=r"pr_review_comments/(?P<comment_id>[0-9]+)",
+ required_scopes=["task:write"],
+ )
+ def pr_review_comment(self, request: Request, *args, **kwargs) -> Response:
+ report = cast(SignalReport, self.get_object())
+ comment_id = str(kwargs["comment_id"])
+ resolved = self._resolve_user_github_and_pr(report, request, comment_id=comment_id)
+ if isinstance(resolved, Response):
+ return resolved
+ user_github, repository, pr_number = resolved
+
+ def run() -> dict[str, Any]:
+ if request.method == "DELETE":
+ return user_github.delete_pull_request_review_comment(repository, comment_id)
+ serializer = PullRequestReviewCommentUpdateSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ return user_github.update_pull_request_review_comment(
+ repository, comment_id, serializer.validated_data["body"]
+ )
+
+ result = self._run_user_github_write(run, repository, pr_number, noun="comment")
+ if isinstance(result, Response):
+ return result
+
+ self._bust_pr_comments_cache(repository, pr_number)
+ if request.method == "DELETE":
+ return Response(status=status.HTTP_204_NO_CONTENT)
+ return self._pr_review_comment_response(result["comment"], status_code=status.HTTP_200_OK)
+
+ @extend_schema(
+ request=PullRequestReviewCommentReactionCreateSerializer,
+ responses={
+ 201: OpenApiResponse(
+ response=PullRequestReviewCommentReactionCreateResponseSerializer,
+ description="The created reaction.",
+ ),
+ 403: OpenApiResponse(description="Not a signed-in user, or no usable personal GitHub connection."),
+ 404: OpenApiResponse(description="Report has no implementation PR, or the comment isn't on it."),
+ 502: OpenApiResponse(description="GitHub rejected the reaction."),
+ 503: OpenApiResponse(description="The GitHub egress budget is temporarily unavailable."),
+ },
+ summary="React to a review comment as the requesting user",
+ operation_id="signals_report_pr_review_comment_reactions_create",
+ parameters=[OpenApiParameter("comment_id", OpenApiTypes.STR, OpenApiParameter.PATH)],
+ )
+ @action(
+ detail=True,
+ methods=["post"],
+ url_path=r"pr_review_comments/(?P<comment_id>[0-9]+)/reactions",
+ required_scopes=["task:write"],
+ )
+ def pr_review_comment_reactions(self, request: Request, *args, **kwargs) -> Response:
+ report = cast(SignalReport, self.get_object())
+ comment_id = str(kwargs["comment_id"])
+ serializer = PullRequestReviewCommentReactionCreateSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ resolved = self._resolve_user_github_and_pr(report, request, comment_id=comment_id)
+ if isinstance(resolved, Response):
+ return resolved
+ user_github, repository, pr_number = resolved
+
+ result = self._run_user_github_write(
+ lambda: user_github.add_pull_request_review_comment_reaction(
+ repository, comment_id, serializer.validated_data["content"]
+ ),
+ repository,
+ pr_number,
+ noun="reaction",
+ )
+ if isinstance(result, Response):
+ return result
+
+ self._bust_pr_comments_cache(repository, pr_number)
+ raw = result.get("reaction") or {}
+ reaction = {
+ "id": str(raw["id"]) if raw.get("id") is not None else "",
+ "content": raw.get("content"),
+ "user_login": (raw.get("user") or {}).get("login"),
+ }
+ return Response({"reaction": reaction}, status=status.HTTP_201_CREATED)
+
+ @extend_schema(
+ responses={
+ 204: OpenApiResponse(description="Reaction removed."),
+ 403: OpenApiResponse(description="Not a signed-in user, or no usable personal GitHub connection."),
+ 404: OpenApiResponse(description="Report has no implementation PR, or the comment isn't on it."),
+ 502: OpenApiResponse(description="GitHub rejected the removal."),
+ 503: OpenApiResponse(description="The GitHub egress budget is temporarily unavailable."),
+ },
+ summary="Remove one of the requesting user's own reactions from a review comment",
+ operation_id="signals_report_pr_review_comment_reaction_destroy",
+ parameters=[
+ OpenApiParameter("comment_id", OpenApiTypes.STR, OpenApiParameter.PATH),
+ OpenApiParameter("reaction_id", OpenApiTypes.STR, OpenApiParameter.PATH),
+ ],
+ )
+ @action(
+ detail=True,
+ methods=["delete"],
+ url_path=r"pr_review_comments/(?P<comment_id>[0-9]+)/reactions/(?P<reaction_id>[0-9]+)",
+ required_scopes=["task:write"],
+ )
+ def pr_review_comment_reaction(self, request: Request, *args, **kwargs) -> Response:
+ report = cast(SignalReport, self.get_object())
+ comment_id = str(kwargs["comment_id"])
+ reaction_id = str(kwargs["reaction_id"])
+ resolved = self._resolve_user_github_and_pr(report, request, comment_id=comment_id)
+ if isinstance(resolved, Response):
+ return resolved
+ user_github, repository, pr_number = resolved
+
+ result = self._run_user_github_write(
+ lambda: user_github.delete_pull_request_review_comment_reaction(repository, comment_id, reaction_id),
+ repository,
+ pr_number,
+ noun="reaction",
+ )
+ if isinstance(result, Response):
+ return result
+ self._bust_pr_comments_cache(repository, pr_number)
+ return Response(status=status.HTTP_204_NO_CONTENT)
+
+ def _bust_pr_comments_cache(self, repository: str, pr_number: int) -> None:
+ """Drop the short PR-comments read cache so a just-made change shows on the next fetch."""
+ cache.delete(f"signals:pr-github:{self.team.id}:{repository}:{pr_number}:get_pull_request_comments")
+
+ @staticmethod
+ def _pr_review_comment_response(raw: object, *, status_code: int) -> Response:
+ """Shape a raw GitHub review comment via the shared read-path normalizer (a fresh write never
+ carries reactions). The shared transport treats a body-less success as valid, so a write result
+ we can't normalize is an upstream failure rather than anything the caller did wrong."""
+ normalized = GitHubIntegrationBase.normalize_pr_comment(raw, "review")
+ if normalized is None:
+ return Response(
+ {"error": "GitHub returned the comment in an unexpected format. Reload to see the latest."},
+ status=status.HTTP_502_BAD_GATEWAY,
+ )
+ return Response({"comment": normalized}, status=status_code)
+
+ def _resolve_user_github_and_pr(
+ self, report: SignalReport, request: Request, *, comment_id: str | None = None
+ ) -> tuple[UserGitHubIntegration, str, int] | Response:
+ """Resolve the requesting user's personal GitHub integration and the report's PR, or a Response
+ error (404 no PR, 403 not a human caller or no personal GitHub connection) to return as-is.
+
+ Every write that reaches GitHub under a human's own identity funnels through here, so the
+ human-caller check lives here too rather than on each action. It admits only a browser
+ session instead of rejecting known token types, because every credential that authenticates
+ *as* the user would otherwise inherit their linked GitHub account: a sandbox agent token is
+ minted as the task actor and carries ``task:write``, and a personal API key holding the same
+ scope is issued for automation rather than for acting as that person on GitHub. Either one
+ could comment, edit, delete, or merge as them.
+
+ ``comment_id``, when given, is resolved and required to sit on the report's own PR. GitHub's
+ review-comment edit, delete, and reaction endpoints are repository-wide, so this is the only
+ thing keeping a report from reaching comments on every other PR in its repository.
+ """
+ if not isinstance(request.successful_authenticator, SessionAuthentication):
+ return Response(
+ {"error": "This must be done by a signed-in user, not an automated token."},
+ status=status.HTTP_403_FORBIDDEN,
+ )
+ user = cast(User, request.user)
+ 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
+ )
+ user_integration = (
+ UserIntegration.objects.filter(user=user, kind=UserIntegration.IntegrationKind.GITHUB)
+ .order_by("created_at")
+ .first()
+ )
+ if user_integration is None:
+ return Response(
+ {"error": "Connect your GitHub account in settings to comment on pull requests."},
+ status=status.HTTP_403_FORBIDDEN,
+ )
+ repository, pr_number = reference
+ user_github = UserGitHubIntegration(user_integration)
+ if comment_id is not None:
+ lookup = self._run_user_github_write(
+ lambda: user_github.get_pull_request_review_comment(repository, comment_id),
+ repository,
+ pr_number,
+ noun="comment",
+ )
+ if isinstance(lookup, Response):
+ return lookup
+ # Matched on the suffix, not the whole URL: the repository is already pinned by the path we
+ # just fetched, while the report's stored PR URL can differ from GitHub's canonical casing.
+ pull_request_url = (lookup.get("comment") or {}).get("pull_request_url")
+ if not isinstance(pull_request_url, str) or not pull_request_url.endswith(f"/pulls/{pr_number}"):
+ return Response(
+ {"error": "This comment isn't on this report's pull request. Refresh the page and try again."},
+ status=status.HTTP_404_NOT_FOUND,
+ )
+ return user_github, repository, pr_number
+
+ def _run_user_github_write(
+ self, fn: Callable[[], dict[str, Any]], repository: str, pr_number: int, *, noun: str
+ ) -> dict[str, Any] | Response:
+ """Run a user-authored GitHub write, mapping the shared failure modes to Responses. Returns the
+ call's result dict on success, or a Response to return as-is. GitHub 403 (e.g. editing someone
+ else's comment) surfaces as a 403."""
+ try:
+ result = fn()
+ except ReauthorizationRequired:
+ return Response(
+ {"error": "Your GitHub connection has expired. Reconnect GitHub in settings."},
+ status=status.HTTP_403_FORBIDDEN,
+ )
+ 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 review {noun} write errored", repository=repository, pr_number=pr_number)
+ return Response({"error": f"GitHub could not accept the {noun}."}, status=status.HTTP_502_BAD_GATEWAY)
+
+ if not result.get("success"):
+ forbidden = result.get("status_code") == 403
+ return Response(
+ {"error": result.get("error") or f"GitHub could not accept the {noun}."},
+ status=status.HTTP_403_FORBIDDEN if forbidden else status.HTTP_502_BAD_GATEWAY,
+ )
+ return result
+
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: ...}``.
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index 1bfd4f6b6439..f3795c5e46fe 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -339,6 +339,21 @@ export const SideEnumApi = {
Right: 'RIGHT',
} as const
+/**
+ * One emoji reaction on a review comment, with the reactor so the viewer's own can be toggled.
+ */
+export interface PullRequestCommentReactionApi {
+ /** GitHub reaction id (needed to remove it). */
+ readonly id: string
+ /** Reaction key: '+1', '-1', 'laugh', 'hooray', 'confused', 'heart', 'rocket', or 'eyes'. */
+ readonly content: string
+ /**
+ * GitHub login of the user who added the reaction.
+ * @nullable
+ */
+ readonly user_login: string | null
+}
+
/**
* One comment on a pull request — a conversation comment or an inline review comment.
*/
@@ -407,6 +422,8 @@ export interface PullRequestCommentApi {
* @nullable
*/
readonly commit_id: string | null
+ /** Emoji reactions on this review comment, one entry per reactor. */
+ readonly reactions: readonly PullRequestCommentReactionApi[]
}
/**
@@ -416,6 +433,107 @@ export interface PullRequestCommentsResponseApi {
readonly comments: readonly PullRequestCommentApi[]
}
+/**
+ * Request body for posting an inline PR review comment as the requesting user.
+ *
+ * Two shapes: a reply to an existing thread (only `body` + `in_reply_to`), or a new
+ * thread on a diff line (`body` + `path` + `line`, optionally `side`).
+ */
+export interface PullRequestReviewCommentCreateApi {
+ /**
+ * Comment body (GitHub-flavored markdown).
+ * @maxLength 65536
+ */
+ body: string
+ /**
+ * Numeric id of the thread root comment to reply to. When set, path/line/side are ignored.
+ * @nullable
+ * @pattern ^[0-9]+$
+ */
+ in_reply_to?: string | null
+ /**
+ * File path to anchor a new comment thread to (required when starting a new thread).
+ * @nullable
+ */
+ path?: string | null
+ /**
+ * Diff line to anchor a new comment thread to (required when starting a new thread).
+ * @minimum 1
+ * @nullable
+ */
+ line?: number | null
+ /** Diff side of the anchor line: 'LEFT' = deletions, 'RIGHT' = additions. Defaults to 'RIGHT'.
+ *
+ * * `LEFT` - LEFT
+ * * `RIGHT` - RIGHT */
+ side?: SideEnumApi | null
+}
+
+/**
+ * Response after posting a review comment — the created comment in the normalized PR-comment shape.
+ */
+export interface PullRequestReviewCommentCreateResponseApi {
+ readonly comment: PullRequestCommentApi
+}
+
+/**
+ * Request body for editing a review comment's markdown body.
+ */
+export interface PatchedPullRequestReviewCommentUpdateApi {
+ /**
+ * New comment body (GitHub-flavored markdown).
+ * @maxLength 65536
+ */
+ body?: string
+}
+
+/**
+ * * `+1` - +1
+ * * `-1` - -1
+ * * `laugh` - laugh
+ * * `hooray` - hooray
+ * * `confused` - confused
+ * * `heart` - heart
+ * * `rocket` - rocket
+ * * `eyes` - eyes
+ */
+export type ContentEnumApi = (typeof ContentEnumApi)[keyof typeof ContentEnumApi]
+
+export const ContentEnumApi = {
+ '1': '+1',
+ NumberMinus1: '-1',
+ Laugh: 'laugh',
+ Hooray: 'hooray',
+ Confused: 'confused',
+ Heart: 'heart',
+ Rocket: 'rocket',
+ Eyes: 'eyes',
+} as const
+
+/**
+ * Request body for adding an emoji reaction to a review comment.
+ */
+export interface PullRequestReviewCommentReactionCreateApi {
+ /** Reaction to add: one of '+1', '-1', 'laugh', 'hooray', 'confused', 'heart', 'rocket', 'eyes'.
+ *
+ * * `+1` - +1
+ * * `-1` - -1
+ * * `laugh` - laugh
+ * * `hooray` - hooray
+ * * `confused` - confused
+ * * `heart` - heart
+ * * `rocket` - rocket
+ * * `eyes` - eyes */
+ content: ContentEnumApi
+}
+
+/**
+ * Response after adding a reaction — the created reaction, so the frontend can track its id.
+ */
+export interface PullRequestReviewCommentReactionCreateResponseApi {
+ readonly reaction: PullRequestCommentReactionApi
+}
+
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 995f3bdf66b6..16e904b0f789 100644
--- a/products/signals/frontend/generated/api.ts
+++ b/products/signals/frontend/generated/api.ts
@@ -23,6 +23,7 @@ import type {
PaginatedSignalReportArtefactListApi,
PaginatedSignalReportListApi,
PaginatedSignalSourceConfigListApi,
+ PatchedPullRequestReviewCommentUpdateApi,
PatchedSignalReportArtefactLogUpdateApi,
PatchedSignalReportContentUpdateApi,
PatchedSignalScoutConfigUpdateApi,
@@ -32,6 +33,10 @@ import type {
ProjectProfileApi,
PullRequestChecksResponseApi,
PullRequestCommentsResponseApi,
+ PullRequestReviewCommentCreateApi,
+ PullRequestReviewCommentCreateResponseApi,
+ PullRequestReviewCommentReactionCreateApi,
+ PullRequestReviewCommentReactionCreateResponseApi,
RememberRequestApi,
ReportSignalsResponseApi,
ScoutEmissionReportLinkApi,
@@ -260,6 +265,125 @@ export const signalsReportPrComments = async (
})
}
+export const getSignalsReportPrReviewCommentsCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/signals/reports/${id}/pr_review_comments/`
+}
+
+/**
+ * Post an inline review comment on the report's implementation pull request, attributed to the requesting user's own GitHub identity via their personal GitHub connection. Either replies to an existing thread (`in_reply_to`) or starts a new thread on a diff line (`path` + `line`).
+ * @summary Post an inline review comment on a report's implementation PR
+ */
+export const signalsReportPrReviewCommentsCreate = async (
+ projectId: string,
+ id: string,
+ pullRequestReviewCommentCreateApi: PullRequestReviewCommentCreateApi,
+ options?: RequestInit
+): Promise<PullRequestReviewCommentCreateResponseApi> => {
+ return apiMutator<PullRequestReviewCommentCreateResponseApi>(
+ getSignalsReportPrReviewCommentsCreateUrl(projectId, id),
+ {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(pullRequestReviewCommentCreateApi),
+ }
+ )
+}
+
+export const getSignalsReportPrReviewCommentUpdateUrl = (projectId: string, id: string, commentId: string) => {
+ return `/api/projects/${projectId}/signals/reports/${id}/pr_review_comments/${commentId}/`
+}
+
+/**
+ * @summary Edit one of the requesting user's own review comments
+ */
+export const signalsReportPrReviewCommentUpdate = async (
+ projectId: string,
+ id: string,
+ commentId: string,
+ patchedPullRequestReviewCommentUpdateApi?: PatchedPullRequestReviewCommentUpdateApi,
+ options?: RequestInit
+): Promise<PullRequestReviewCommentCreateResponseApi> => {
+ return apiMutator<PullRequestReviewCommentCreateResponseApi>(
+ getSignalsReportPrReviewCommentUpdateUrl(projectId, id, commentId),
+ {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(patchedPullRequestReviewCommentUpdateApi),
+ }
+ )
+}
+
+export const getSignalsReportPrReviewCommentDestroyUrl = (projectId: string, id: string, commentId: string) => {
+ return `/api/projects/${projectId}/signals/reports/${id}/pr_review_comments/${commentId}/`
+}
+
+/**
+ * @summary Delete one of the requesting user's own review comments
+ */
+export const signalsReportPrReviewCommentDestroy = async (
+ projectId: string,
+ id: string,
+ commentId: string,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getSignalsReportPrReviewCommentDestroyUrl(projectId, id, commentId), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
+export const getSignalsReportPrReviewCommentReactionsCreateUrl = (projectId: string, id: string, commentId: string) => {
+ return `/api/projects/${projectId}/signals/reports/${id}/pr_review_comments/${commentId}/reactions/`
+}
+
+/**
+ * @summary React to a review comment as the requesting user
+ */
+export const signalsReportPrReviewCommentReactionsCreate = async (
+ projectId: string,
+ id: string,
+ commentId: string,
+ pullRequestReviewCommentReactionCreateApi: PullRequestReviewCommentReactionCreateApi,
+ options?: RequestInit
+): Promise<PullRequestReviewCommentReactionCreateResponseApi> => {
+ return apiMutator<PullRequestReviewCommentReactionCreateResponseApi>(
+ getSignalsReportPrReviewCommentReactionsCreateUrl(projectId, id, commentId),
+ {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(pullRequestReviewCommentReactionCreateApi),
+ }
+ )
+}
+
+export const getSignalsReportPrReviewCommentReactionDestroyUrl = (
+ projectId: string,
+ id: string,
+ commentId: string,
+ reactionId: string
+) => {
+ return `/api/projects/${projectId}/signals/reports/${id}/pr_review_comments/${commentId}/reactions/${reactionId}/`
+}
+
+/**
+ * @summary Remove one of the requesting user's own reactions from a review comment
+ */
+export const signalsReportPrReviewCommentReactionDestroy = async (
+ projectId: string,
+ id: string,
+ commentId: string,
+ reactionId: string,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getSignalsReportPrReviewCommentReactionDestroyUrl(projectId, id, commentId, reactionId), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
export const getSignalsReportsRefundCreateUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/signals/reports/${id}/refund/`
}
diff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.ts
index b44a2ca12613..7d781d6e1783 100644
--- a/products/signals/frontend/generated/api.zod.ts
+++ b/products/signals/frontend/generated/api.zod.ts
@@ -47,6 +47,76 @@ export const SignalsReportsPartialUpdateBody = /* @__PURE__ */ zod
'Editable human-facing fields on a signal report (PATCH).\n\nBoth fields are optional so a caller can change either independently, but at least one\nmust be supplied. Every other report field — status, weights, judgments — is owned by the\nsignals pipeline and is deliberately not writable here.'
)
+/**
+ * Post an inline review comment on the report's implementation pull request, attributed to the requesting user's own GitHub identity via their personal GitHub connection. Either replies to an existing thread (`in_reply_to`) or starts a new thread on a diff line (`path` + `line`).
+ * @summary Post an inline review comment on a report's implementation PR
+ */
+export const signalsReportPrReviewCommentsCreateBodyBodyMax = 65536
+
+export const signalsReportPrReviewCommentsCreateBodyInReplyToRegExp = new RegExp('^[0-9]+$')
+
+export const SignalsReportPrReviewCommentsCreateBody = /* @__PURE__ */ zod
+ .object({
+ body: zod
+ .string()
+ .max(signalsReportPrReviewCommentsCreateBodyBodyMax)
+ .describe('Comment body (GitHub-flavored markdown).'),
+ in_reply_to: zod
+ .string()
+ .regex(signalsReportPrReviewCommentsCreateBodyInReplyToRegExp)
+ .nullish()
+ .describe('Numeric id of the thread root comment to reply to. When set, path\/line\/side are ignored.'),
+ path: zod
+ .string()
+ .nullish()
+ .describe('File path to anchor a new comment thread to (required when starting a new thread).'),
+ line: zod
+ .number()
+ .min(1)
+ .nullish()
+ .describe('Diff line to anchor a new comment thread to (required when starting a new thread).'),
+ side: zod
+ .union([zod.enum(['LEFT', 'RIGHT']).describe('\* `LEFT` - LEFT\n\* `RIGHT` - RIGHT'), zod.null()])
+ .optional()
+ .describe(
+ "Diff side of the anchor line: 'LEFT' = deletions, 'RIGHT' = additions. Defaults to 'RIGHT'.\n\n\* `LEFT` - LEFT\n\* `RIGHT` - RIGHT"
+ ),
+ })
+ .describe(
+ 'Request body for posting an inline PR review comment as the requesting user.\n\nTwo shapes: a reply to an existing thread (only `body` + `in_reply_to`), or a new\nthread on a diff line (`body` + `path` + `line`, optionally `side`).'
+ )
+
+/**
+ * @summary Edit one of the requesting user's own review comments
+ */
+export const signalsReportPrReviewCommentUpdateBodyBodyMax = 65536
+
+export const SignalsReportPrReviewCommentUpdateBody = /* @__PURE__ */ zod
+ .object({
+ body: zod
+ .string()
+ .max(signalsReportPrReviewCommentUpdateBodyBodyMax)
+ .optional()
+ .describe('New comment body (GitHub-flavored markdown).'),
+ })
+ .describe("Request body for editing a review comment's markdown body.")
+
+/**
+ * @summary React to a review comment as the requesting user
+ */
+export const SignalsReportPrReviewCommentReactionsCreateBody = /* @__PURE__ */ zod
+ .object({
+ content: zod
+ .enum(['+1', '-1', 'laugh', 'hooray', 'confused', 'heart', 'rocket', 'eyes'])
+ .describe(
+ '\* `+1` - +1\n\* `-1` - -1\n\* `laugh` - laugh\n\* `hooray` - hooray\n\* `confused` - confused\n\* `heart` - heart\n\* `rocket` - rocket\n\* `eyes` - eyes'
+ )
+ .describe(
+ "Reaction to add: one of '+1', '-1', 'laugh', 'hooray', 'confused', 'heart', 'rocket', 'eyes'.\n\n\* `+1` - +1\n\* `-1` - -1\n\* `laugh` - laugh\n\* `hooray` - hooray\n\* `confused` - confused\n\* `heart` - heart\n\* `rocket` - rocket\n\* `eyes` - eyes"
+ ),
+ })
+ .describe('Request body for adding an emoji reaction to a review comment.')
+
/**
* Refund the flat charge for this report's implementation PR and archive the report. Refunds auto-approve: the charge is either excluded from usage before it is ever reported to billing (refund on the same UTC day as the PR run) or returned as a Stripe customer-balance credit on the next invoice. A refunded PR does not count toward the free monthly PR allowance. One refund per report, ever — repeat calls return the existing refund with already_refunded=true. The report is archived as part of the refund (a resolved report stays resolved) and can't be restored afterwards.
* @summary Refund a report's implementation PR
diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yaml
index f48b6db5c5db..013337d52bdb 100644
--- a/products/signals/mcp/tools.yaml
+++ b/products/signals/mcp/tools.yaml
@@ -825,6 +825,21 @@ tools:
signals-report-pr-comments:
operation: signals_report_pr_comments
enabled: false
+ signals-report-pr-review-comment-destroy:
+ operation: signals_report_pr_review_comment_destroy
+ enabled: false
+ signals-report-pr-review-comment-reaction-destroy:
+ operation: signals_report_pr_review_comment_reaction_destroy
+ enabled: false
+ signals-report-pr-review-comment-reactions-create:
+ operation: signals_report_pr_review_comment_reactions_create
+ enabled: false
+ signals-report-pr-review-comment-update:
+ operation: signals_report_pr_review_comment_update
+ enabled: false
+ signals-report-pr-review-comments-create:
+ operation: signals_report_pr_review_comments_create
+ 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 f045deaa9616..42835bfcc6c4 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -14459,6 +14459,30 @@ export namespace Schemas {
Base64: 'base64',
} as const;
+ /**
+ * * `+1` - +1
+ * * `-1` - -1
+ * * `laugh` - laugh
+ * * `hooray` - hooray
+ * * `confused` - confused
+ * * `heart` - heart
+ * * `rocket` - rocket
+ * * `eyes` - eyes
+ */
+ export type ContentEnum = typeof ContentEnum[keyof typeof ContentEnum];
+
+
+ export const ContentEnum = {
+ '1': '+1',
+ NumberMinus1: '-1',
+ Laugh: 'laugh',
+ Hooray: 'hooray',
+ Confused: 'confused',
+ Heart: 'heart',
+ Rocket: 'rocket',
+ Eyes: 'eyes',
+ } as const;
+
export interface ContextGeneration {
/**
* ID of the Task currently generating this folder's CONTEXT.md, or null if none.
@@ -46966,6 +46990,11 @@ export namespace Schemas {
repository_selection?: string | null;
/** Installation account metadata from GitHub. */
account?: UserGitHubAccount | null;
+ /**
+ * The connected user's own GitHub login (distinct from the installation account).
+ * @nullable
+ */
+ github_login?: string | null;
/** True when this installation id matches a team-level GitHub integration on the active project. */
uses_shared_installation: boolean;
/** When this integration row was created. */
@@ -52689,6 +52718,17 @@ export namespace Schemas {
scopes?: string[];
}
+ /**
+ * Request body for editing a review comment's markdown body.
+ */
+ export interface PatchedPullRequestReviewCommentUpdate {
+ /**
+ * New comment body (GitHub-flavored markdown).
+ * @maxLength 65536
+ */
+ body?: string;
+ }
+
export interface PatchedQueryTabState {
readonly id?: string;
/**
@@ -57514,6 +57554,21 @@ export namespace Schemas {
Right: 'RIGHT',
} as const;
+ /**
+ * One emoji reaction on a review comment, with the reactor so the viewer's own can be toggled.
+ */
+ export interface PullRequestCommentReaction {
+ /** GitHub reaction id (needed to remove it). */
+ readonly id: string;
+ /** Reaction key: '+1', '-1', 'laugh', 'hooray', 'confused', 'heart', 'rocket', or 'eyes'. */
+ readonly content: string;
+ /**
+ * GitHub login of the user who added the reaction.
+ * @nullable
+ */
+ readonly user_login: string | null;
+ }
+
/**
* One comment on a pull request — a conversation comment or an inline review comment.
*/
@@ -57582,6 +57637,8 @@ export namespace Schemas {
* @nullable
*/
readonly commit_id: string | null;
+ /** Emoji reactions on this review comment, one entry per reactor. */
+ readonly reactions: readonly PullRequestCommentReaction[];
}
/**
@@ -57667,6 +57724,73 @@ export namespace Schemas {
limit: number;
}
+ /**
+ * Request body for posting an inline PR review comment as the requesting user.
+ *
+ * Two shapes: a reply to an existing thread (only `body` + `in_reply_to`), or a new
+ * thread on a diff line (`body` + `path` + `line`, optionally `side`).
+ */
+ export interface PullRequestReviewCommentCreate {
+ /**
+ * Comment body (GitHub-flavored markdown).
+ * @maxLength 65536
+ */
+ body: string;
+ /**
+ * Numeric id of the thread root comment to reply to. When set, path/line/side are ignored.
+ * @nullable
+ * @pattern ^[0-9]+$
+ */
+ in_reply_to?: string | null;
+ /**
+ * File path to anchor a new comment thread to (required when starting a new thread).
+ * @nullable
+ */
+ path?: string | null;
+ /**
+ * Diff line to anchor a new comment thread to (required when starting a new thread).
+ * @minimum 1
+ * @nullable
+ */
+ line?: number | null;
+ /** Diff side of the anchor line: 'LEFT' = deletions, 'RIGHT' = additions. Defaults to 'RIGHT'.
+ *
+ * * `LEFT` - LEFT
+ * * `RIGHT` - RIGHT */
+ side?: SideEnum | null;
+ }
+
+ /**
+ * Response after posting a review comment — the created comment in the normalized PR-comment shape.
+ */
+ export interface PullRequestReviewCommentCreateResponse {
+ readonly comment: PullRequestComment;
+ }
+
+ /**
+ * Request body for adding an emoji reaction to a review comment.
+ */
+ export interface PullRequestReviewCommentReactionCreate {
+ /** Reaction to add: one of '+1', '-1', 'laugh', 'hooray', 'confused', 'heart', 'rocket', 'eyes'.
+ *
+ * * `+1` - +1
+ * * `-1` - -1
+ * * `laugh` - laugh
+ * * `hooray` - hooray
+ * * `confused` - confused
+ * * `heart` - heart
+ * * `rocket` - rocket
+ * * `eyes` - eyes */
+ content: ContentEnum;
+ }
+
+ /**
+ * Response after adding a reaction — the created reaction, so the frontend can track its id.
+ */
+ export interface PullRequestReviewCommentReactionCreateResponse {
+ readonly reaction: PullRequestCommentReaction;
+ }
+
/**
* * `ios` - iOS
* * `android` - Android