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(signals): Close the loop between support tickets and agent research (#73646)

Michael Matloka22b56f50cca3
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 835995e19140..dd4a361df506 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -7122,6 +7122,18 @@ snapshots:
hash: v1.k794b7964.0fd64e1c397852c809ef69724691610ab9ad359e2d08d6c733b5f9ead6aa8291.dwo2_aCUYE-BT1n22S0mcFO-v5T-UqzbJ31LnUL50KA
scenes-app-sidepanels--side-panel-support--light:
hash: v1.k794b7964.87cae042d1f0a60a2c843a358cbb0c3ef2acd60284df8de0e84b9b7eb8d5084f.VMPQg6ury8nhCzIjULK0WgJTTN5h0vnVM4OZTx3A8ig
+ scenes-app-support-threadreportentry--fix-merged--dark:
+ hash: v1.k794b7964.9b2ed403c9a96a40cdf57d0a8e6c71b8dab6f7a9343d17b16eba6d8b6d8cfe02.ubF_YTSkWvY2MEUK_U1jXy3Obh2NuJZDG7swlz7hEIs
+ scenes-app-support-threadreportentry--fix-merged--light:
+ hash: v1.k794b7964.829ae3009955f65e20e347921b596b84f053b63c0fefb7628200d15bc24ca4dc.s0B8u3UrlfAm03SqC5h276_MQeB4dxpKQ7OfyYC3sCU
+ scenes-app-support-threadreportentry--fix-proposed--dark:
+ hash: v1.k794b7964.08572f013c4bebfa0cd3394b5bb15caa83bf8873a9ca6a6a0177141a0484b334.QNpHsOagxzWzpatB99DXnUwqAVNOKoea71jHT6_wQrI
+ scenes-app-support-threadreportentry--fix-proposed--light:
+ hash: v1.k794b7964.88ff8b7ba4a60d059ca11c9b5ff8198feacc2f54bb876a482f5e38b64530ee6e.LgTD4VhKBOqNkpnDR7tGvkLOENb1gQs8F9wf-Ib4Pp4
+ scenes-app-support-threadreportentry--several-reports-across-states--dark:
+ hash: v1.k794b7964.bd7bb412a5652df533ddaaee34979952c4cc563214fdb9da0c2341c2ee3a42c0.2_uB4JqMmb5VC1ApVDY0uQTkdcOPfwsLn0EROX92oS4
+ scenes-app-support-threadreportentry--several-reports-across-states--light:
+ hash: v1.k794b7964.cda6dcd93ae53690e576d7cd55346d52945f7ab5a02ac997e71e2f57966ead0f.XW-a_SkxIsORQ3W4LRuIka6w6cMIRiv4ALyfr55J2i8
scenes-app-surveys--new-multi-question-survey-section--dark:
hash: v1.k794b7964.e4c838e9c192c01eab518de2435a2fef6d3ed65b727fe4c05af61eee010bf03d.yIm_bRCN_65TxDwWd9qVeapTEfZ5QAYSmpJbKKle8Hw
scenes-app-surveys--new-multi-question-survey-section--light:
diff --git a/frontend/src/lib/signals/SignalReportPrBadge.tsx b/frontend/src/lib/signals/SignalReportPrBadge.tsx
new file mode 100644
index 000000000000..7835d3386e02
--- /dev/null
+++ b/frontend/src/lib/signals/SignalReportPrBadge.tsx
@@ -0,0 +1,43 @@
+import { IconPullRequest } from '@posthog/icons'
+import { LemonTag, Link, Tooltip } from '@posthog/lemon-ui'
+
+import { PR_BADGE_STATE, type PrBadgeState } from './prState'
+
+/**
+ * PR status badge for the card's top-right corner: a state-colored tag with the pull-request
+ * icon and `#1234`. When a PR URL is known the whole badge is the GitHub link itself.
+ */
+export function PrBadge({
+ prNumber,
+ prUrl,
+ state,
+}: {
+ prNumber: string
+ prUrl?: string | null
+ state: PrBadgeState
+}): JSX.Element {
+ const { label, type } = PR_BADGE_STATE[state]
+ const badge = (
+ <LemonTag type={type} size="small" icon={<IconPullRequest />} className="font-mono tabular-nums">
+ #{prNumber}
+ </LemonTag>
+ )
+
+ if (!prUrl) {
+ return <Tooltip title={`Pull request #${prNumber} (${label})`}>{badge}</Tooltip>
+ }
+
+ return (
+ <Tooltip title={`Open pull request #${prNumber} (${label}) on GitHub`}>
+ <Link
+ to={prUrl}
+ target="_blank"
+ disableClientSideRouting
+ onClick={(e) => e.stopPropagation()}
+ aria-label={`Open pull request #${prNumber} (${label}) on GitHub`}
+ >
+ {badge}
+ </Link>
+ </Tooltip>
+ )
+}
diff --git a/frontend/src/lib/signals/prState.ts b/frontend/src/lib/signals/prState.ts
new file mode 100644
index 000000000000..455fb09f3e3d
--- /dev/null
+++ b/frontend/src/lib/signals/prState.ts
@@ -0,0 +1,31 @@
+import type { LemonTagType } from '@posthog/lemon-ui'
+
+import { SignalReportStatus } from '~/scenes/inbox/types'
+
+/**
+ * PR open/merged/closed state, mapped to muted palette tags (outlined: --success / --purple /
+ * --danger). "merged" comes from `implementation_pr_merged`, the flag the GitHub webhook sets on
+ * merge — report status can't stand in for it, since a report can be resolved directly without its
+ * PR ever landing. A failed report means the PR never landed; everything else is still an open PR.
+ *
+ * Shared so every surface that shows a report's PR agrees on what its state means, including the
+ * support ticket sidebar, where "did this ship?" is the question a teammate is answering.
+ */
+export const PR_BADGE_STATE: Record<'open' | 'merged' | 'closed', { label: string; type: LemonTagType }> = {
+ open: { label: 'open', type: 'success' },
+ merged: { label: 'merged', type: 'completion' },
+ closed: { label: 'closed', type: 'danger' },
+}
+
+export type PrBadgeState = keyof typeof PR_BADGE_STATE
+
+/** `status` is widened to string so callers holding the generated API enum can pass it directly. */
+export function derivePrState(status: SignalReportStatus | string, prMerged: boolean): PrBadgeState {
+ if (prMerged) {
+ return 'merged'
+ }
+ if (status === SignalReportStatus.FAILED) {
+ return 'closed'
+ }
+ return 'open'
+}
diff --git a/frontend/src/scenes/inbox/components/badges/SignalReportStatusBadge.tsx b/frontend/src/scenes/inbox/components/badges/SignalReportStatusBadge.tsx
index 831e94e40f17..862696b9b0f5 100644
--- a/frontend/src/scenes/inbox/components/badges/SignalReportStatusBadge.tsx
+++ b/frontend/src/scenes/inbox/components/badges/SignalReportStatusBadge.tsx
@@ -2,7 +2,7 @@ import { LemonTag, LemonTagType, Tooltip } from '@posthog/lemon-ui'
import { SignalReportStatus } from '../../types'
-const STATUS_TOOLTIPS: Partial<Record<SignalReportStatus, string>> = {
+export const STATUS_TOOLTIPS: Partial<Record<SignalReportStatus, string>> = {
[SignalReportStatus.READY]: 'Research is complete. You can create a task from this report.',
[SignalReportStatus.PENDING_INPUT]: 'This report needs human input in PostHog before it can proceed.',
[SignalReportStatus.IN_PROGRESS]: "An AI agent is actively researching this report's findings.",
@@ -14,7 +14,7 @@ const STATUS_TOOLTIPS: Partial<Record<SignalReportStatus, string>> = {
[SignalReportStatus.DELETED]: 'This report has been deleted.',
}
-const STATUS_LABELS: Partial<Record<SignalReportStatus, string>> = {
+export const STATUS_LABELS: Partial<Record<SignalReportStatus, string>> = {
[SignalReportStatus.READY]: 'Ready',
[SignalReportStatus.PENDING_INPUT]: 'Needs input',
[SignalReportStatus.IN_PROGRESS]: 'Researching',
diff --git a/frontend/src/scenes/inbox/components/cards/ReportCard.tsx b/frontend/src/scenes/inbox/components/cards/ReportCard.tsx
index cab8eb638897..3e5303205180 100644
--- a/frontend/src/scenes/inbox/components/cards/ReportCard.tsx
+++ b/frontend/src/scenes/inbox/components/cards/ReportCard.tsx
@@ -1,12 +1,14 @@
import clsx from 'clsx'
import { router } from 'kea-router'
-import { IconArchive, IconPullRequest, IconUndo } from '@posthog/icons'
-import { LemonButton, LemonTag, LemonTagType, Link, Tooltip } from '@posthog/lemon-ui'
+import { IconArchive, IconUndo } from '@posthog/icons'
+import { LemonButton, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'
import { TZLabel } from 'lib/components/TZLabel'
+import { derivePrState } from 'lib/signals/prState'
import { ScoutLink } from 'lib/signals/ScoutLink'
import { scoutDisplayName } from 'lib/signals/signalCardSourceLine'
+import { PrBadge } from 'lib/signals/SignalReportPrBadge'
import { urls } from 'scenes/urls'
import { InboxFlatListTabKey, SignalReport, SignalReportStatus, SignalSourceProduct } from '../../types'
@@ -83,69 +85,6 @@ export function InboxCardSourceMeta({
// ── PR status badge ─────────────────────────────────────────────────────────
-/**
- * PR open/merged/closed state, mapped to muted palette tags (outlined: --success / --purple /
- * --danger). "merged" comes from `implementation_pr_merged`, the flag the GitHub webhook sets on
- * merge — report status can't stand in for it, since a report can be resolved directly without its
- * PR ever landing. A failed report means the PR never landed; everything else is still an open PR.
- */
-const PR_BADGE_STATE: Record<'open' | 'merged' | 'closed', { label: string; type: LemonTagType }> = {
- open: { label: 'open', type: 'success' },
- merged: { label: 'merged', type: 'completion' },
- closed: { label: 'closed', type: 'danger' },
-}
-
-type PrBadgeState = keyof typeof PR_BADGE_STATE
-
-function derivePrState(status: SignalReportStatus, prMerged: boolean): PrBadgeState {
- if (prMerged) {
- return 'merged'
- }
- if (status === SignalReportStatus.FAILED) {
- return 'closed'
- }
- return 'open'
-}
-
-/**
- * PR status badge for the card's top-right corner: a state-colored tag with the pull-request
- * icon and `#1234`. When a PR URL is known the whole badge is the GitHub link itself.
- */
-function PrBadge({
- prNumber,
- prUrl,
- state,
-}: {
- prNumber: string
- prUrl?: string | null
- state: PrBadgeState
-}): JSX.Element {
- const { label, type } = PR_BADGE_STATE[state]
- const badge = (
- <LemonTag type={type} size="small" icon={<IconPullRequest />} className="font-mono tabular-nums">
- #{prNumber}
- </LemonTag>
- )
-
- if (!prUrl) {
- return <Tooltip title={`Pull request #${prNumber} (${label})`}>{badge}</Tooltip>
- }
-
- return (
- <Tooltip title={`Open pull request #${prNumber} (${label}) on GitHub`}>
- <Link
- to={prUrl}
- target="_blank"
- disableClientSideRouting
- onClick={(e) => e.stopPropagation()}
- aria-label={`Open pull request #${prNumber} (${label}) on GitHub`}
- >
- {badge}
- </Link>
- </Tooltip>
- )
-}
-
// ── ReportCard ────────────────────────────────────────────────────────────────
/**
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 10309ff1bdbc..7893e4fc2163 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -2878,6 +2878,9 @@ importers:
'@posthog/lemon-ui':
specifier: '*'
version: 0.0.0([email protected]([email protected])([email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected])))([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))([email protected]([email protected]))([email protected])
+ '@storybook/react':
+ specifier: 'catalog:'
'@tiptap/core':
specifier: 3.20.6
version: 3.20.6(@tiptap/[email protected])
@@ -20516,6 +20519,10 @@ packages:
peerDependencies:
typescript: 6.0.3
+ resolution: {integrity: sha512-+NRMYs2DyTP4/tqWz371Oo50JqmWltR1h2gcdgUMAWZJIAvrd0/SqlCfx7tpzpl/s36rzw6qH2MjoNrxtRNYhA==}
+ engines: {node: ^20.9.0 || >=22}
+
resolution: {integrity: sha512-aEZ9qP+/M+58x2qgfSFEWH1BxLyHe5+qkLNJOZQb5iGS017jpbRnoKhNRrXPeA6RfBrZO5wZrT9DMC1UqE1f1w==}
engines: {node: ^20.9.0 || >=22}
@@ -22536,8 +22543,8 @@ packages:
resolution: {integrity: sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==}
engines: {node: '>= 10.0.0'}
- resolution: {integrity: sha512-4GPU1YED5+X9ynAQw/cWnOez5pCcamkB++PQjfHIEQwqmsagOYkbxKPWqu1s4lcg6iJ1lZte33EeLqiTFV4u8g==}
+ resolution: {integrity: sha512-36kWwjzwSgz++3RuL6p6uXRaV36G/V+sM9jRz2e3Gu5634vf95z7kdj8vld2UW/NBRZb/NLkjXf8MPSacU6oQw==}
resolution: {integrity: sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==}
@@ -31755,7 +31762,7 @@ snapshots:
'@storybook/global': 5.0.0
react: 18.3.1
- react-docgen: 8.0.3
+ react-docgen: 8.0.2
react-docgen-typescript: 2.2.2([email protected])
react-dom: 18.3.1([email protected])
@@ -31771,7 +31778,7 @@ snapshots:
'@storybook/global': 5.0.0
react: 18.3.1
- react-docgen: 8.0.3
+ react-docgen: 8.0.2
react-docgen-typescript: 2.2.2([email protected])
react-dom: 18.3.1([email protected])
@@ -43327,6 +43334,21 @@ snapshots:
dependencies:
typescript: 6.0.3
+ dependencies:
+ '@babel/core': 7.29.0
+ '@babel/traverse': 7.29.0
+ '@babel/types': 7.29.0
+ '@types/babel__core': 7.20.5
+ '@types/babel__traverse': 7.28.0
+ '@types/doctrine': 0.0.9
+ '@types/resolve': 1.20.6
+ doctrine: 3.0.0
+ resolve: 1.22.8
+ strip-indent: 4.0.0
+ transitivePeerDependencies:
+ - supports-color
+
dependencies:
'@babel/core': 7.29.0
@@ -43358,7 +43380,7 @@ snapshots:
dependencies:
react: 18.3.1
- unlayer-types: 1.457.0
+ unlayer-types: 1.449.0
dependencies:
@@ -45686,7 +45708,7 @@ snapshots:
diff --git a/products/conversations/backend/facade/api.py b/products/conversations/backend/facade/api.py
index eccc8a7db9b0..a1be2c0795db 100644
--- a/products/conversations/backend/facade/api.py
+++ b/products/conversations/backend/facade/api.py
@@ -11,8 +11,10 @@ from typing import Any
from pydantic.dataclasses import dataclass
from slack_sdk.errors import SlackApiError
+from posthog.models.comment import Comment
from posthog.models.team import Team
+from products.conversations.backend.models import Ticket
from products.conversations.backend.slack import get_slack_client
from products.conversations.backend.support_slack_channels import (
SupportSlackChannelsUnavailable as SupportSlackChannelsUnavailable,
@@ -106,3 +108,33 @@ def post_support_message(team_id: int, channel_id: str, text: str) -> str:
if not ts:
raise SupportMessageSendError("missing_ts")
return ts
+
+
+def post_ticket_internal_note(team_id: int, ticket_id: str, content: str, *, dedupe_key: str) -> str | None:
+ """Add a team-only note to a ticket, as the AI author. Returns the new comment's id, or None when
+ nothing was written because the ticket doesn't exist for this team or this ``dedupe_key`` already
+ posted a note.
+
+ Always private: callers use this to hand agent findings to a support teammate, who decides what
+ (if anything) reaches the customer. ``dedupe_key`` identifies the thing that produced the note so
+ a retrying caller doesn't post twice.
+ """
+ if not Ticket.objects.filter(team_id=team_id, id=ticket_id).exists():
+ return None
+ already_posted = Comment.objects.filter(
+ team_id=team_id,
+ scope="conversations_ticket",
+ item_id=ticket_id,
+ item_context__internal_note_key=dedupe_key,
+ deleted=False,
+ ).exists()
+ if already_posted:
+ return None
+ comment = Comment.objects.create(
+ team_id=team_id,
+ scope="conversations_ticket",
+ item_id=ticket_id,
+ content=content,
+ item_context={"author_type": "AI", "is_private": True, "internal_note_key": dedupe_key},
+ )
+ return str(comment.id)
diff --git a/products/conversations/backend/temporal/ai_reply/activities/classify.py b/products/conversations/backend/temporal/ai_reply/activities/classify.py
index d53dde667471..155cbaa32e7e 100644
--- a/products/conversations/backend/temporal/ai_reply/activities/classify.py
+++ b/products/conversations/backend/temporal/ai_reply/activities/classify.py
@@ -33,12 +33,13 @@ Classify the ticket into exactly one type and propose search queries to start re
ticket_type — one of:
- how_to: any question the customer wants answered that can be addressed from documentation or the team's knowledge base — product usage ("how do I X"), as well as questions about the company, its policies, security/vulnerability reporting, legal/terms, pricing info, and similar. When in doubt between how_to and unactionable, choose how_to.
-- diagnostic: the customer reports something broken, failing, or behaving unexpectedly for their account; answering it requires investigating their actual data.
+- diagnostic: something looks wrong for this customer specifically, and answering it requires investigating their own data or configuration.
+- bug: the customer reports the product itself misbehaving in a way that looks like a defect for anyone, not just them - a hang, a crash, wrong output, or something that used to work and stopped. Choose bug over diagnostic when the described behavior is not what the product is supposed to do at all.
- account_billing: a question about the customer's plan, usage, limits, invoices, or billing.
- unactionable: ONLY spam, bare feedback/thanks with no question, or automated noise. If the customer is asking anything they want answered, do NOT use this type.
Return a JSON object with these keys:
-- ticket_type: one of how_to | diagnostic | account_billing | unactionable.
+- ticket_type: one of how_to | diagnostic | account_billing | bug | unactionable.
- needs_diagnostics: boolean — true only when answering requires looking at the customer's own data (typically diagnostic tickets).
- seed_queries: list of 2-4 concise search queries (strings) that would find relevant docs/knowledge; empty list for unactionable.
diff --git a/products/conversations/backend/temporal/ai_reply/constants.py b/products/conversations/backend/temporal/ai_reply/constants.py
index a55fcb72c839..1bd42ff35c05 100644
--- a/products/conversations/backend/temporal/ai_reply/constants.py
+++ b/products/conversations/backend/temporal/ai_reply/constants.py
@@ -44,9 +44,11 @@ VALIDATOR_MODEL = "claude-sonnet-4-6"
LLM_REQUEST_TIMEOUT_SECONDS = 90.0
# One-shot triage of each ticket up front. `how_to`/`account_billing` are retrieval-solvable;
-# `diagnostic` needs the customer's own data (drives PR 3's wider read scopes); `unactionable`
-# (spam, bare feedback, no question) short-circuits before the expensive draft loop.
-TICKET_TYPES = ("how_to", "diagnostic", "account_billing", "unactionable")
+# `diagnostic` needs the customer's own data (drives PR 3's wider read scopes); `bug` is answered by
+# researching our own code, which the signals pipeline does separately and writes back onto the
+# ticket; `unactionable` (spam, bare feedback, no question) short-circuits before the expensive
+# draft loop.
+TICKET_TYPES = ("how_to", "diagnostic", "account_billing", "bug", "unactionable")
# Scopes for a reply that may be auto-sent to the (untrusted) ticket author. Deliberately the
# narrowest set: only what docs-search (project:read) and business-knowledge search
@@ -97,4 +99,10 @@ TICKET_TYPE_HINTS: dict[str, str] = {
"diagnostic": "This is a diagnostic ticket — the customer reports something broken or unexpected for their account; focus on what's failing and why.",
"account_billing": "This is an account/billing question — focus on the customer's plan, usage, limits, and billing specifics.",
"unactionable": "This ticket has no answerable support question.",
+ "bug": (
+ "This reads as a defect in the product itself, not a usage or account question. Do not offer a fix or a "
+ "workaround assembled from documentation, because the behavior described is not what the docs describe. "
+ "Acknowledge the report and gather only what an engineer would need to reproduce it: affected version or SDK, "
+ "exact steps, when it started, error text, and screenshots."
+ ),
}
diff --git a/products/conversations/backend/temporal/tests/test_pipeline.py b/products/conversations/backend/temporal/tests/test_pipeline.py
index a67082939a80..b11d170fc178 100644
--- a/products/conversations/backend/temporal/tests/test_pipeline.py
+++ b/products/conversations/backend/temporal/tests/test_pipeline.py
@@ -446,6 +446,12 @@ class TestPersistReplyActivity:
{"widget": {"diagnostic": "bot_reply"}},
True,
),
+ (
+ "bug_stays_private_even_if_set_to_bot_reply",
+ {"allow_bot_reply": True, "channel_source": "widget", "ticket_type": "bug"},
+ {"widget": {"bug": "bot_reply"}},
+ True,
+ ),
(
"account_billing_stays_private_even_if_set_to_bot_reply",
{"allow_bot_reply": True, "channel_source": "widget", "ticket_type": "account_billing"},
diff --git a/products/conversations/frontend/components/Chat/ChatView.tsx b/products/conversations/frontend/components/Chat/ChatView.tsx
index ceea2ff1a553..84a892ffe6b3 100644
--- a/products/conversations/frontend/components/Chat/ChatView.tsx
+++ b/products/conversations/frontend/components/Chat/ChatView.tsx
@@ -4,7 +4,7 @@ import { LemonCard } from '@posthog/lemon-ui'
import type { AiReplyFeedbackRating, ChatMessage, Ticket, TicketChannel, TicketStatus } from '../../types'
import { MessageInput } from './MessageInput'
-import { MessageList } from './MessageList'
+import { MessageList, type TimelineExtra } from './MessageList'
export interface ChatViewProps {
messages: ChatMessage[]
@@ -42,6 +42,8 @@ export interface ChatViewProps {
onPrivateChange?: (isPrivate: boolean) => void
/** Extra actions rendered next to the send button in MessageInput */
extraActions?: React.ReactNode
+ /** Non-message thread entries, placed by their own timestamp (e.g. team-only agent findings) */
+ threadExtras?: TimelineExtra[]
/** Blocks sending customer-facing messages (private notes stay available) */
replyDisabledReason?: string | JSX.Element
/** Whether draft mode is on: tints the composer green and confirms the recipient before sending */
@@ -78,6 +80,7 @@ export function ChatView({
draftContent,
onDraftChange,
isPrivate,
+ threadExtras,
onPrivateChange,
extraActions,
replyDisabledReason,
@@ -112,6 +115,7 @@ export function ChatView({
feedbackByMessageId={feedbackByMessageId}
showAiReplyFeedback={showAiReplyFeedback}
onSubmitAiReplyFeedback={onSubmitAiReplyFeedback}
+ extras={threadExtras}
/>
<div className="border-t pt-3">
<MessageInput
diff --git a/products/conversations/frontend/components/Chat/Message.tsx b/products/conversations/frontend/components/Chat/Message.tsx
index 45b0b0d3c33c..2d01cafb30d4 100644
--- a/products/conversations/frontend/components/Chat/Message.tsx
+++ b/products/conversations/frontend/components/Chat/Message.tsx
@@ -3,7 +3,6 @@ import { useRef, useState } from 'react'
import {
IconCopy,
- IconLock,
IconThumbsDown,
IconThumbsDownFilled,
IconThumbsUp,
@@ -17,6 +16,7 @@ import { copyToClipboard } from 'lib/utils/copyToClipboard'
import type { AiReplyFeedbackRating, ChatMessage, MessageDeliveryStatus } from '../../types'
import { SupportMarkdown, SupportRichContentPreview } from '../Editor'
+import { TeamOnlyBadge } from './TeamOnlyBadge'
export interface MessageProps {
message: ChatMessage
@@ -75,14 +75,7 @@ export function Message({
showName={true}
/>
<div className="flex items-center gap-1.5">
- {isPrivate && (
- <Tooltip title="Only visible to your team">
- <span className="inline-flex items-center gap-0.5 text-xs text-warning-dark bg-warning-highlight px-1.5 py-0.5 rounded">
- <IconLock className="text-xs" />
- Private note
- </span>
- </Tooltip>
- )}
+ {isPrivate && <TeamOnlyBadge label="Private note" />}
<span className="text-xs text-muted-alt">
<TZLabel time={message.createdAt} />
</span>
@@ -110,13 +103,18 @@ export function Message({
</Tooltip>
</div>
)}
+ {/* Every message here is untrusted: customers write them, imports carry them,
+ and agents generate them from customer text. An inline remote image would
+ fetch on open, leaking the reader's IP or probing hosts their browser can
+ reach. PostHog-hosted images (attachments included) still render inline;
+ anything else becomes a click-to-open link. */}
{message.richContent ? (
<SupportRichContentPreview
content={message.richContent as JSONContent}
className="text-sm"
/>
) : (
- <SupportMarkdown className="text-sm" disableImages={message.fromZendesk}>
+ <SupportMarkdown className="text-sm" disableImages>
{message.content}
</SupportMarkdown>
)}
diff --git a/products/conversations/frontend/components/Chat/MessageList.tsx b/products/conversations/frontend/components/Chat/MessageList.tsx
index 7621ff8a09aa..4c54b5bad1c2 100644
--- a/products/conversations/frontend/components/Chat/MessageList.tsx
+++ b/products/conversations/frontend/components/Chat/MessageList.tsx
@@ -28,6 +28,16 @@ export interface MessageListProps {
/** Whether AI reply feedback controls are enabled */
showAiReplyFeedback?: boolean
onSubmitAiReplyFeedback?: (messageId: string, rating: AiReplyFeedbackRating, feedbackText?: string) => void
+ /** Non-message timeline entries, placed among the messages by their own timestamp. Opt-in, so a
+ * customer-facing view never receives team-only content. */
+ extras?: TimelineExtra[]
+}
+
+/** A non-message entry in the thread, e.g. an agent's findings. `at` is what orders it among the
+ * messages; `element` carries its own React key. */
+export interface TimelineExtra {
+ at: string
+ element: JSX.Element
}
export function MessageList({
@@ -47,6 +57,7 @@ export function MessageList({
feedbackByMessageId = {},
showAiReplyFeedback = false,
onSubmitAiReplyFeedback,
+ extras = [],
}: MessageListProps): JSX.Element {
const messagesEndRef = useRef<HTMLDivElement>(null)
const containerRef = useRef<HTMLDivElement>(null)
@@ -61,10 +72,11 @@ export function MessageList({
}
useEffect(() => {
- if (messages.length > 0) {
+ if (messages.length > 0 || extras.length > 0) {
scrollToBottom()
}
- }, [messages.length])
+ // Extras land in the same stream, so one arriving has to scroll like a message does.
+ }, [messages.length, extras.length])
const handleScroll = (): void => {
const container = containerRef.current
@@ -103,6 +115,41 @@ export function MessageList({
const deliveryStatusMap = getDeliveryStatusMap()
+ // Messages and extras share one chronological stream, so an agent's findings sit at the point in
+ // the conversation they arrived rather than always at the bottom. Ties keep messages first, and
+ // the original order within each kind, so a same-second reply never reshuffles.
+ const timeline: JSX.Element[] = [
+ ...messages.map((message) => {
+ const isCustomer = message.authorType === 'customer'
+ return {
+ at: message.createdAt,
+ rank: 0,
+ element: (
+ <Message
+ key={message.id}
+ message={message}
+ isCustomer={isCustomerView ? !isCustomer : isCustomer}
+ deliveryStatus={deliveryStatusMap.get(message.id)}
+ showAiReplyFeedback={
+ showAiReplyFeedback && message.id === latestAiMessageId && message.authorType === 'AI'
+ }
+ aiReplyFeedbackRating={feedbackByMessageId[message.id] ?? null}
+ onSubmitAiReplyFeedback={
+ onSubmitAiReplyFeedback
+ ? (rating, feedbackText) => onSubmitAiReplyFeedback(message.id, rating, feedbackText)
+ : undefined
+ }
+ />
+ ),
+ }
+ }),
+ ...extras.map((extra) => ({ at: extra.at, rank: 1, element: extra.element })),
+ ]
+ // Array.prototype.sort is stable, so equal (time, rank) pairs keep the order they were
+ // concatenated in; only the message-before-extra tiebreak needs stating.
+ .sort((a, b) => new Date(a.at).getTime() - new Date(b.at).getTime() || a.rank - b.rank)
+ .map(({ element }) => element)
+
return (
<div
ref={containerRef}
@@ -123,29 +170,7 @@ export function MessageList({
<div className="flex items-center justify-center h-full text-muted-alt text-sm">{emptyMessage}</div>
) : (
<>
- {messages.map((message) => {
- const isCustomer = message.authorType === 'customer'
- return (
- <Message
- key={message.id}
- message={message}
- isCustomer={isCustomerView ? !isCustomer : isCustomer}
- deliveryStatus={deliveryStatusMap.get(message.id)}
- showAiReplyFeedback={
- showAiReplyFeedback &&
- message.id === latestAiMessageId &&
- message.authorType === 'AI'
- }
- aiReplyFeedbackRating={feedbackByMessageId[message.id] ?? null}
- onSubmitAiReplyFeedback={
- onSubmitAiReplyFeedback
- ? (rating, feedbackText) =>
- onSubmitAiReplyFeedback(message.id, rating, feedbackText)
- : undefined
- }
- />
- )
- })}
+ {timeline}
<div ref={messagesEndRef} />
</>
)}
diff --git a/products/conversations/frontend/components/Chat/TeamOnlyBadge.tsx b/products/conversations/frontend/components/Chat/TeamOnlyBadge.tsx
new file mode 100644
index 000000000000..fb6bacb71bb9
--- /dev/null
+++ b/products/conversations/frontend/components/Chat/TeamOnlyBadge.tsx
@@ -0,0 +1,20 @@
+import { IconLock } from '@posthog/icons'
+import { Tooltip } from '@posthog/lemon-ui'
+
+/**
+ * Marks a thread entry as team-only. Shared because the thread's whole purpose is sending things to
+ * customers, so "the customer cannot see this" has to look identical wherever it appears: one badge,
+ * one tooltip, no chance of two surfaces drifting into two different-looking promises.
+ *
+ * `label` varies because what's being withheld varies: a note someone wrote, versus an agent's findings.
+ */
+export function TeamOnlyBadge({ label }: { label: string }): JSX.Element {
+ return (
+ <Tooltip title="Only visible to your team">
+ <span className="inline-flex items-center gap-0.5 text-xs text-warning-dark bg-warning-highlight px-1.5 py-0.5 rounded">
+ <IconLock className="text-xs" />
+ {label}
+ </span>
+ </Tooltip>
+ )
+}
diff --git a/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx b/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx
index 0c6b87c303b4..98ed5803ce30 100644
--- a/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx
+++ b/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx
@@ -37,6 +37,7 @@ import { RelatedGroupsPanel } from './RelatedGroupsPanel'
import { SessionRecordingPanel } from './SessionRecordingPanel'
import { StaffActionsPanel } from './StaffActionsPanel'
import { supportTicketSceneLogic } from './supportTicketSceneLogic'
+import { reportTimelineExtras } from './ThreadReports'
import { TicketActivityPanel } from './TicketActivityPanel'
// The list's filters / saved view ride along in the ticket page's query string
@@ -83,6 +84,7 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.Elem
eventsQuery,
previousTickets,
previousTicketsLoading,
+ linkedReports,
exceptionsQuery,
chatPanelWidth,
hasUnsavedChanges,
@@ -208,6 +210,7 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.Elem
>
{/* Main conversation area */}
<ChatView
+ threadExtras={reportTimelineExtras(linkedReports)}
messages={chatMessages}
messagesLoading={messagesLoading}
messageSending={messageSending}
diff --git a/products/conversations/frontend/scenes/ticket/ThreadReports.stories.tsx b/products/conversations/frontend/scenes/ticket/ThreadReports.stories.tsx
new file mode 100644
index 000000000000..fa521ed8d98e
--- /dev/null
+++ b/products/conversations/frontend/scenes/ticket/ThreadReports.stories.tsx
@@ -0,0 +1,76 @@
+import type { Meta, StoryObj } from '@storybook/react'
+
+import type { SignalReportApi } from 'products/signals/frontend/generated/api.schemas'
+
+import { ThreadReportEntry } from './ThreadReports'
+
+// The thread entry a support teammate reads on a ticket to see which reports came out of it.
+// A ticket's fix is the headline, so the PR states get their own stories.
+
+const meta: Meta<typeof ThreadReportEntry> = {
+ title: 'Scenes-App/Support/ThreadReportEntry',
+ component: ThreadReportEntry,
+ parameters: { layout: 'padded', viewMode: 'story', mockDate: '2026-07-25' },
+}
+export default meta
+
+type Story = StoryObj<typeof ThreadReportEntry>
+
+function makeReport(overrides: Partial<SignalReportApi>): SignalReportApi {
+ return {
+ id: '019f9582-93e7-77c1-8912-4f541d70cb13',
+ status: 'ready',
+ title: 'perf(agent): cut latency on formatting-only edits',
+ summary:
+ 'Formatting-only edits re-run full query generation, so a one-line change costs the same as a new question.\n\n## Problem\n\nThe agent rebuilds its whole plan per turn, and a formatting edit takes the same path as a fresh query.',
+ implementation_pr_url: 'https://github.com/PostHog/posthog/pull/73646',
+ implementation_pr_merged: false,
+ ...overrides,
+ } as SignalReportApi
+}
+
+function Thread({ children }: { children: React.ReactNode }): JSX.Element {
+ return <div className="max-w-2xl">{children}</div>
+}
+
+export const FixProposed: Story = {
+ render: () => (
+ <Thread>
+ <ThreadReportEntry report={makeReport({})} />
+ </Thread>
+ ),
+}
+
+export const FixMerged: Story = {
+ render: () => (
+ <Thread>
+ <ThreadReportEntry report={makeReport({ implementation_pr_merged: true })} />
+ </Thread>
+ ),
+}
+
+export const SeveralReportsAcrossStates: Story = {
+ render: () => (
+ <Thread>
+ <ThreadReportEntry report={makeReport({})} />
+ <ThreadReportEntry
+ report={makeReport({
+ id: '019f954a-8ed0-7a18-a198-3ffed1a2def0',
+ status: 'in_progress',
+ title: 'fix(agent): stop dropping chat history mid-run',
+ summary: 'The session is re-keyed when a tool call times out, so the thread restarts empty.',
+ implementation_pr_url: null,
+ })}
+ />
+ <ThreadReportEntry
+ report={makeReport({
+ id: '019f9569-5d45-780a-8b63-ecd0dc71148e',
+ status: 'pending_input',
+ title: null,
+ summary: 'Needs a product call on whether this should be rate-limited per project.',
+ implementation_pr_url: null,
+ })}
+ />
+ </Thread>
+ ),
+}
diff --git a/products/conversations/frontend/scenes/ticket/ThreadReports.tsx b/products/conversations/frontend/scenes/ticket/ThreadReports.tsx
new file mode 100644
index 000000000000..4e3c5bb81791
--- /dev/null
+++ b/products/conversations/frontend/scenes/ticket/ThreadReports.tsx
@@ -0,0 +1,129 @@
+import { Link, Tooltip } from '@posthog/lemon-ui'
+
+import { Logomark } from 'lib/brand'
+import { TZLabel } from 'lib/components/TZLabel'
+import { derivePrState, type PrBadgeState } from 'lib/signals/prState'
+import { PrBadge } from 'lib/signals/SignalReportPrBadge'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
+import { urls } from 'scenes/urls'
+
+import { STATUS_LABELS, STATUS_TOOLTIPS } from '~/scenes/inbox/components/badges/SignalReportStatusBadge'
+import type { SignalReportStatus } from '~/scenes/inbox/types'
+import {
+ deriveHeadline,
+ displayConventionalCommitTitle,
+ parsePrUrlParts,
+ safeHttpUrl,
+} from '~/scenes/inbox/utils/reportPresentation'
+
+import type { SignalReportApi } from 'products/signals/frontend/generated/api.schemas'
+
+import type { TimelineExtra } from '../../components/Chat/MessageList'
+import { TeamOnlyBadge } from '../../components/Chat/TeamOnlyBadge'
+
+/** The inbox's own labels are written to stand alone in a badge, so this surface phrases the same
+ * states as a sentence a teammate can act on. The state derivation stays shared. */
+const FIX_LABEL: Record<PrBadgeState, string> = {
+ open: 'Fix proposed',
+ merged: 'Fix merged',
+ closed: 'Fix closed',
+}
+
+/**
+ * Whether it shipped, which is what a teammate answering the customer most needs. A pull request says
+ * that better than the report's own status, so the status is the fallback rather than a second badge:
+ * either there's no PR, or its URL doesn't parse as one.
+ *
+ * `PrBadge` brings the link, state colour, and the external-link and accessibility handling the inbox
+ * already got right.
+ */
+function FixOrStatus({ report }: { report: SignalReportApi }): JSX.Element {
+ // The URL comes from an agent's raw task-run output and isn't scheme-validated server-side.
+ const prUrl = safeHttpUrl(report.implementation_pr_url)
+ const prNumber = prUrl ? parsePrUrlParts(prUrl)?.number : undefined
+ if (prUrl && prNumber) {
+ const state = derivePrState(report.status, report.implementation_pr_merged)
+ return (
+ <div className="flex items-center gap-1.5">
+ <span className="text-xs font-semibold">{FIX_LABEL[state]}</span>
+ <PrBadge prNumber={prNumber} prUrl={prUrl} state={state} />
+ </div>
+ )
+ }
+ const statusKey = report.status as SignalReportStatus
+ const label = STATUS_LABELS[statusKey] ?? report.status
+ // The inbox badge always explains itself on hover, falling back to the label; match that.
+ return (
+ <Tooltip title={STATUS_TOOLTIPS[statusKey] ?? label}>
+ <span className="text-xs text-muted-alt">{label}</span>
+ </Tooltip>
+ )
+}
+
+/**
+ * One report, as an entry in the ticket thread.
+ *
+ * The thread is a place where people talk to customers, so this has to read as three things at a
+ * glance: not a person, not sent to anyone, and about this conversation. It wears the PostHog mark
+ * instead of an avatar, names the agent rather than a human, keeps the thread's own private-note
+ * lock, and deliberately avoids the message bubble so it doesn't scan as something anybody said.
+ */
+export function ThreadReportEntry({ report }: { report: SignalReportApi }): JSX.Element {
+ const headline = deriveHeadline(report.summary)
+ // Full width, unlike a message: messages are inset because they belong to one side of the
+ // conversation, and this belongs to neither.
+ return (
+ <div className="mb-4">
+ {/* Same header structure as a message: who on the left, then the facts about this entry
+ clustered on the right, so the thread keeps one rhythm down the page. */}
+ <div className="flex items-center justify-between w-full gap-2 mb-1">
+ <div className="flex items-center gap-1.5 min-w-0">
+ {/* The PostHog mark rather than an avatar: this is our software acting, not a
+ teammate with a profile. Mono and theme-following so it reads as a byline next to
+ the name instead of competing with it. Height comes from a class because the size
+ tokens start at 20px, and it lands just under a message avatar's 18px: small
+ enough to sit on the same rhythm, big enough to still read as the PostHog mark. */}
+ <Logomark variant="mono" color="primary" className="h-4 w-auto shrink-0" />
+ <span className="text-sm font-medium">Self-driving</span>
+ <Tooltip title="A PostHog agent that investigates tickets against your codebase. Not a teammate.">
+ <span className="text-xs text-muted-alt">PostHog agent</span>
+ </Tooltip>
+ </div>
+ <div className="flex items-center gap-1.5 shrink-0">
+ <TeamOnlyBadge label="Internal" />
+ <span className="text-xs text-muted-alt">
+ <TZLabel time={report.updated_at} />
+ </span>
+ </div>
+ </div>
+ {/* Not a bubble, and marked down its edge, so it never reads as something a person said.
+ The edge is a pseudo-element so it can run the full height without fighting the border
+ radius the way a left border does. */}
+ <div className="relative flex items-start justify-between gap-3 overflow-hidden rounded border border-primary bg-surface-primary transition-colors hover:border-secondary py-2 pl-4 pr-3 after:content-[''] after:absolute after:inset-y-0 after:left-0 after:w-1 after:bg-accent">
+ {/* The link takes the whole left column so the entry reads as one target, while the
+ state stays a sibling: an anchor can't contain another, and clicking the pull
+ request should open the pull request. */}
+ <Link
+ to={urls.inboxReport('reports', report.id)}
+ className="block min-w-0 flex-1 text-inherit no-underline hover:text-inherit"
+ >
+ <div className="text-sm font-semibold leading-snug">
+ {capitalizeFirstLetter(displayConventionalCommitTitle(report.title, 'Untitled report'))}
+ </div>
+ {headline && <p className="mt-0.5 mb-0 text-xs text-muted leading-snug">{headline}</p>}
+ </Link>
+ <div className="shrink-0">
+ <FixOrStatus report={report} />
+ </div>
+ </div>
+ </div>
+ )
+}
+
+/** Reports as thread entries, ordered by when each was last updated. */
+export function reportTimelineExtras(linkedReports: SignalReportApi[]): TimelineExtra[] {
+ return linkedReports.map((report) => ({
+ at: report.updated_at,
+ element: <ThreadReportEntry key={report.id} report={report} />,
+ }))
+}
diff --git a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts
index c53e222573e9..64c1334f39df 100644
--- a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts
+++ b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts
@@ -39,6 +39,8 @@ import {
businessKnowledgeGapSuggestionsDismissCreate,
businessKnowledgeGapSuggestionsList,
} from 'products/business_knowledge/frontend/generated/api'
+import { signalsReportsList } from 'products/signals/frontend/generated/api'
+import type { SignalReportApi } from 'products/signals/frontend/generated/api.schemas'
import type { TeamPublicType, TeamType } from '../../../../../frontend/src/types'
import type { UserType } from '../../../../../frontend/src/types'
@@ -190,6 +192,8 @@ export interface supportTicketSceneLogicValues {
knowledgeGaps: KnowledgeGapSuggestion[]
knowledgeGapsLoading: boolean
latestAiMessage: ChatMessage | null
+ linkedReports: SignalReportApi[]
+ linkedReportsLoading: boolean
messageSending: boolean
messages: CommentType[]
messagesLoading: boolean
@@ -241,6 +245,27 @@ export interface supportTicketSceneLogicActions {
value: true
}
}
+ loadLinkedReports: () => {
+ value: true
+ }
+ loadLinkedReportsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadLinkedReportsSuccess: (
+ linkedReports: SignalReportApi[],
+ payload?: {
+ value: true
+ }
+ ) => {
+ linkedReports: SignalReportApi[]
+ payload?: {
+ value: true
+ }
+ }
loadMessages: () => {
value: true
}
@@ -478,6 +503,7 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([
// Session context actions
loadPerson: true,
loadPreviousTickets: true,
+ loadLinkedReports: true,
// Knowledge gap suggestions
loadKnowledgeGaps: true,
@@ -525,6 +551,29 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([
},
},
],
+ linkedReports: [
+ [] as SignalReportApi[],
+ {
+ loadLinkedReports: async (): Promise<SignalReportApi[]> => {
+ const ticketUuid = values.ticket?.id
+ if (!ticketUuid) {
+ return []
+ }
+ try {
+ const response = await signalsReportsList(getCurrentTeamId().toString(), {
+ source_id: ticketUuid,
+ source_product: 'conversations',
+ include_all_statuses: true,
+ })
+ return response.results || []
+ } catch (error) {
+ // Supplementary context: a signals or ClickHouse hiccup must not break the ticket.
+ console.error('Failed to load linked reports:', error)
+ return []
+ }
+ },
+ },
+ ],
previousTickets: [
[] as Ticket[],
{
@@ -941,6 +990,7 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([
// Load session context data
actions.loadPerson()
actions.loadKnowledgeGaps()
+ actions.loadLinkedReports()
// Refresh the unread count since viewing a ticket marks it as read
supportTicketCounterLogic.findMounted()?.actions.refreshCount()
diff --git a/products/conversations/package.json b/products/conversations/package.json
index c0597d836c09..67a8bf7b666c 100644
--- a/products/conversations/package.json
+++ b/products/conversations/package.json
@@ -21,6 +21,7 @@
"peerDependencies": {
"@posthog/icons": "catalog:",
"@posthog/lemon-ui": "*",
+ "@storybook/react": "catalog:",
"@testing-library/jest-dom": "*",
"@testing-library/react": "*",
"@testing-library/user-event": "*",
diff --git a/products/signals/backend/emission/fetchers/conversations.py b/products/signals/backend/emission/fetchers/conversations.py
index 598a79411df8..5e0e6e69073b 100644
--- a/products/signals/backend/emission/fetchers/conversations.py
+++ b/products/signals/backend/emission/fetchers/conversations.py
@@ -2,7 +2,7 @@ from datetime import timedelta
from typing import Any
from django.db.models import CharField, Exists, OuterRef, Q
-from django.db.models.functions import Cast
+from django.db.models.functions import Cast, Coalesce
from django.utils import timezone
import structlog
@@ -17,10 +17,13 @@ from products.signals.backend.models import SignalEmissionRecord
logger = structlog.get_logger(__name__)
-# Cooldown period before a ticket is eligible for signal emission.
-# Vibes, ensures some conversation context has accumulated.
-# TODO: Use last_message_at instead of created_at so we snapshot after the thread goes quiet, not just after creation.
-TICKET_COOLDOWN_HOURS = 1
+# How long a thread must be quiet before it is snapshotted. Keyed off the last message rather than
+# ticket creation, because the decisive detail in a support thread (the repro, the error text, the
+# escalation) usually arrives in a reply, not the opening message.
+TICKET_QUIET_PERIOD_HOURS = 1
+# Floor between successive snapshots of the same ticket. A thread that keeps going gets re-read, but
+# at most once a window, so a chatty ticket can't emit a signal per lull.
+TICKET_RESNAPSHOT_MIN_INTERVAL_HOURS = 24
def conversations_ticket_fetcher(
@@ -30,20 +33,26 @@ def conversations_ticket_fetcher(
) -> list[dict[str, Any]]:
"""Fetch conversation tickets from Postgres and record emission in SignalEmissionRecord."""
now = timezone.now()
- cutoff = now - timedelta(hours=TICKET_COOLDOWN_HOURS)
+ quiet_since = now - timedelta(hours=TICKET_QUIET_PERIOD_HOURS)
+ resnapshot_floor = now - timedelta(hours=TICKET_RESNAPSHOT_MIN_INTERVAL_HOURS)
lookback = now - timedelta(days=config.first_sync_lookback_days)
- # Pick tickets we haven't emitted signals for yet (NOT EXISTS subquery)
- already_emitted = SignalEmissionRecord.objects.filter(
+ # Quiet for long enough, measured from the last message when there is one. Tickets predating
+ # last_message_at backfill fall back to created_at.
+ thread_is_quiet = Q(last_message_at__lte=quiet_since) | Q(last_message_at__isnull=True, created_at__lte=quiet_since)
+ # Skip a ticket when we already snapshotted it at or after its latest message (nothing new to
+ # read), or when the last snapshot is too recent to take another.
+ snapshot_still_current = SignalEmissionRecord.objects.filter(
team=team,
source_product=config.source_product,
source_type=config.source_type,
source_id=Cast(OuterRef("id"), output_field=CharField()),
+ ).filter(
+ Q(emitted_at__gte=Coalesce(OuterRef("last_message_at"), OuterRef("created_at")))
+ | Q(emitted_at__gte=resnapshot_floor)
+ )
+ tickets_qs = Ticket.objects.filter(team=team, created_at__gte=lookback).filter(
+ thread_is_quiet, ~Exists(snapshot_still_current)
)
- tickets_qs = Ticket.objects.filter(
- team=team,
- created_at__gte=lookback,
- created_at__lte=cutoff,
- ).filter(~Exists(already_emitted))
if config.where_clause:
# nosemgrep: python.django.security.audit.query-set-extra.avoid-query-set-extra (where_clause is a hardcoded config constant, not user input)
tickets_qs = tickets_qs.extra(where=[config.where_clause])
@@ -88,7 +97,8 @@ def conversations_ticket_fetcher(
ticket_id = str(ticket["id"])
ticket["messages"] = comments_by_ticket.get(ticket_id, [])
ticket["image_attachments"] = images_by_ticket.get(ticket_id, [])
- # Record emission optimistically
+ # Record emission optimistically. Upsert rather than ignore conflicts, because a re-snapshotted
+ # ticket already has a row and its emitted_at is what gates the next one.
# TODO: Revisit if signal loss on transient pipeline failure becomes a concern
SignalEmissionRecord.objects.bulk_create(
[
@@ -101,6 +111,8 @@ def conversations_ticket_fetcher(
)
for tid in ticket_ids
],
- ignore_conflicts=True,
+ update_conflicts=True,
+ update_fields=["emitted_at"],
+ unique_fields=["team", "source_product", "source_type", "source_id"],
)
return tickets
diff --git a/products/signals/backend/emission/tests/test_conversations_fetcher.py b/products/signals/backend/emission/tests/test_conversations_fetcher.py
index 9d6b0f01eca1..386c234ef5df 100644
--- a/products/signals/backend/emission/tests/test_conversations_fetcher.py
+++ b/products/signals/backend/emission/tests/test_conversations_fetcher.py
@@ -33,6 +33,16 @@ def _backdate_ticket(ticket, hours=2):
Ticket.objects.filter(id=ticket.id).update(created_at=timezone.now() - timedelta(hours=hours))
+def _set_last_message_at(ticket, minutes_ago):
+ Ticket.objects.filter(id=ticket.id).update(last_message_at=timezone.now() - timedelta(minutes=minutes_ago))
+
+
+def _backdate_emission(team, ticket, hours):
+ SignalEmissionRecord.objects.filter(team=team, source_id=str(ticket.id)).update(
+ emitted_at=timezone.now() - timedelta(hours=hours)
+ )
+
+
def _add_comment(team, ticket, content="Hello", author_type="customer", deleted=False, rich_content=None):
return Comment.objects.create(
team=team,
@@ -73,6 +83,36 @@ class TestConversationsTicketFetcherEligibility(BaseTest):
second = conversations_ticket_fetcher(self.team, CONVERSATIONS_TICKETS_CONFIG, {})
assert second == []
+ def test_ticket_still_being_replied_to_is_not_fetched(self):
+ ticket = _make_ticket(self.team)
+ _backdate_ticket(ticket, hours=6)
+ _set_last_message_at(ticket, minutes_ago=5)
+
+ assert conversations_ticket_fetcher(self.team, CONVERSATIONS_TICKETS_CONFIG, {}) == []
+
+ def test_ticket_is_resnapshotted_once_new_messages_land(self):
+ ticket = _make_ticket(self.team)
+ _backdate_ticket(ticket, hours=48)
+ assert len(conversations_ticket_fetcher(self.team, CONVERSATIONS_TICKETS_CONFIG, {})) == 1
+
+ _backdate_emission(self.team, ticket, hours=30)
+ _set_last_message_at(ticket, minutes_ago=90)
+
+ resnapshot = conversations_ticket_fetcher(self.team, CONVERSATIONS_TICKETS_CONFIG, {})
+ assert [t["id"] for t in resnapshot] == [ticket.id]
+ # The re-snapshot must advance the ledger, or the ticket would be fetched on every run.
+ assert conversations_ticket_fetcher(self.team, CONVERSATIONS_TICKETS_CONFIG, {}) == []
+
+ def test_new_messages_within_the_resnapshot_interval_are_not_fetched(self):
+ ticket = _make_ticket(self.team)
+ _backdate_ticket(ticket, hours=48)
+ assert len(conversations_ticket_fetcher(self.team, CONVERSATIONS_TICKETS_CONFIG, {})) == 1
+
+ _backdate_emission(self.team, ticket, hours=2)
+ _set_last_message_at(ticket, minutes_ago=90)
+
+ assert conversations_ticket_fetcher(self.team, CONVERSATIONS_TICKETS_CONFIG, {}) == []
+
@pytest.mark.django_db
class TestConversationsTicketFetcherMessages(BaseTest):
diff --git a/products/signals/backend/support_writeback.py b/products/signals/backend/support_writeback.py
new file mode 100644
index 000000000000..1bf79c50cf16
--- /dev/null
+++ b/products/signals/backend/support_writeback.py
@@ -0,0 +1,85 @@
+"""Returns a ready report's findings to the support ticket that raised it.
+
+Support tickets flow into the inbox as signals, get researched against the codebase, and the result
+lands in the inbox only. The teammate answering the customer never sees it, so they reply from what
+they knew before the research ran. This posts the findings back onto the ticket as a private note for
+them to draw on, which closes the loop without putting agent output in front of a customer.
+"""
+
+from __future__ import annotations
+
+from django.conf import settings
+
+import structlog
+
+from posthog.models import Team
+
+from products.conversations.backend.facade import api as conversations_facade
+from products.signals.backend.enums import SignalSourceProduct
+from products.signals.backend.models import SignalReport
+
+logger = structlog.get_logger(__name__)
+
+
+def _note_body(report_url: str) -> str:
+ """A pointer, deliberately carrying none of the report's own content.
+
+ Comments authorize as the `comment` resource while reports authorize as `task`, so a teammate with
+ ticket access but no inbox access can read this note. Copying the title or summary here would hand
+ them research they aren't entitled to; a link makes them pass the report's own access check. The
+ ticket's Associated reports panel reads through that check, so the findings still surface in the
+ ticket for anyone allowed to see them.
+ """
+ return (
+ f"**Self-driving investigated this ticket.** Internal note, not sent to the customer.\n\nFindings: {report_url}"
+ )
+
+
+def post_report_findings_to_tickets(team: Team, report_id: str, signals: list[dict]) -> int:
+ """Post a ready report's findings as a private note on each support ticket that contributed to it.
+
+ Returns the number of notes posted. Best-effort: a failure here must not fail the report's
+ notification flow, so per-ticket errors are logged rather than raised.
+ """
+ ticket_ids = sorted(
+ {
+ str(signal.get("source_id") or "")
+ for signal in signals
+ if signal.get("source_product") == SignalSourceProduct.CONVERSATIONS and signal.get("source_id")
+ }
+ )
+ if not ticket_ids:
+ return 0
+
+ if not SignalReport.objects.filter(id=report_id, team_id=team.pk).exists():
+ return 0
+
+ body = _note_body(f"{settings.SITE_URL}/project/{team.pk}/inbox/{report_id}")
+
+ posted = 0
+ for ticket_id in ticket_ids:
+ try:
+ comment_id = conversations_facade.post_ticket_internal_note(
+ team_id=team.pk,
+ ticket_id=ticket_id,
+ content=body,
+ dedupe_key=f"signals_report:{report_id}",
+ )
+ except Exception:
+ logger.exception(
+ "Failed to post signals findings to support ticket",
+ report_id=report_id,
+ ticket_id=ticket_id,
+ team_id=team.pk,
+ )
+ continue
+ if comment_id is not None:
+ posted += 1
+ logger.info(
+ "Posted signals findings to support tickets",
+ report_id=report_id,
+ team_id=team.pk,
+ tickets=len(ticket_ids),
+ posted=posted,
+ )
+ return posted
diff --git a/products/signals/backend/temporal/inbox_notification.py b/products/signals/backend/temporal/inbox_notification.py
index f6ececd324dc..3a11f6a1cad7 100644
--- a/products/signals/backend/temporal/inbox_notification.py
+++ b/products/signals/backend/temporal/inbox_notification.py
@@ -24,6 +24,7 @@ from posthog.temporal.common.scoped import scoped_temporal
from products.signals.backend.implementation_pr import fetch_implementation_pr_urls_for_reports
from products.signals.backend.models import SignalReport
+from products.signals.backend.support_writeback import post_report_findings_to_tickets
from products.signals.backend.task_run_artefacts import SIGNALS_PRODUCT, TASK_RUN_TYPE_IMPLEMENTATION
from products.signals.backend.temporal.signal_queries import fetch_signals_for_report_sync
from products.tasks.backend.facade import api as tasks_facade
@@ -96,6 +97,14 @@ def _send_report_inbox_notifications(team_id: int, report_id: str) -> int:
# Re-derive source products at send time so a deferred notification reflects the current signals.
signals = fetch_signals_for_report_sync(team, report_id)
source_products = sorted({s["source_product"] for s in signals if s.get("source_product")})
+ # Point any support ticket that raised this report at it. Shares this function's READY guard.
+ # Guarded here as well as inside: the write-back is supplementary, and letting it raise would fail
+ # the activity before the Slack notification below, so a retry loop would drop the notification
+ # entirely over a side errand.
+ try:
+ post_report_findings_to_tickets(team, report_id, signals)
+ except Exception:
+ logger.exception("inbox notification: support write-back failed", report_id=report_id, team_id=team_id)
return dispatch_inbox_item_notifications(
report_id=report_id,
team_id=team_id,
diff --git a/products/signals/backend/temporal/signal_queries.py b/products/signals/backend/temporal/signal_queries.py
index 6719f04a84d8..a96a11b2e62c 100644
--- a/products/signals/backend/temporal/signal_queries.py
+++ b/products/signals/backend/temporal/signal_queries.py
@@ -726,3 +726,61 @@ def fetch_report_ids_for_source_ids(team: Team, source_ids: list[str]) -> dict[s
)
return {row[0]: row[1] for row in (result.results or []) if row[0] and row[1]}
+
+
+def fetch_live_report_ids_for_source_ids(
+ team: Team, source_ids: list[str], source_product: str | None = None
+) -> dict[str, list[str]]:
+ """Map each `source_id` to every live report its signals grouped into, newest report first.
+
+ Sibling of `fetch_report_ids_for_source_ids`, which answers a different question: that one
+ collapses to the single latest report because a scout finding's re-emit is non-idempotent and
+ the older link is stale. A source record can legitimately produce several distinct signals over
+ time (a support ticket is re-snapshotted as its thread grows), and those can land in different
+ reports, so here every live link is a real answer rather than a stale one.
+
+ Dedup runs per `document_id` first, so each signal contributes its current report and deleted
+ state; only then are deleted and report-less signals dropped. Doing it in that order is what
+ keeps a superseded version of a signal from resurrecting an old link.
+ """
+ if not source_ids:
+ return {}
+
+ source_id_scan_filter = "JSONExtractString(metadata, 'source_id') IN ({source_ids})"
+ product_filter = "AND source_product = {source_product}" if source_product is not None else ""
+ ch_query = f"""
+ SELECT source_id, groupArray(report_id) as report_ids
+ FROM (
+ SELECT
+ JSONExtractString(metadata, 'source_id') as source_id,
+ JSONExtractString(metadata, 'report_id') as report_id,
+ JSONExtractBool(metadata, 'deleted') as is_deleted,
+ JSONExtractString(metadata, 'source_product') as source_product,
+ max(timestamp) as latest_timestamp
+ FROM ({_deduped_signals_subquery(extra_where=source_id_scan_filter)})
+ GROUP BY source_id, report_id, is_deleted, source_product
+ ORDER BY latest_timestamp DESC
+ )
+ WHERE NOT is_deleted
+ AND source_id != ''
+ AND report_id != ''
+ {product_filter}
+ GROUP BY source_id
+ """
+
+ placeholders: dict[str, ast.Expr] = {
+ "model_name": ast.Constant(value=EMBEDDING_MODEL.value),
+ "source_ids": ast.Tuple(exprs=[ast.Constant(value=sid) for sid in source_ids]),
+ }
+ if source_product is not None:
+ placeholders["source_product"] = ast.Constant(value=source_product)
+
+ tag_queries(product=Product.SIGNALS, feature=Feature.QUERY)
+ result = execute_hogql_query(
+ query_type="SignalsFetchLiveReportIdsForSourceIds",
+ query=ch_query,
+ team=team,
+ placeholders=placeholders,
+ )
+
+ return {row[0]: list(row[1]) for row in (result.results or []) if row[0] and row[1]}
diff --git a/products/signals/backend/test/test_reports_source_id_filter.py b/products/signals/backend/test/test_reports_source_id_filter.py
new file mode 100644
index 000000000000..e2247e7039fd
--- /dev/null
+++ b/products/signals/backend/test/test_reports_source_id_filter.py
@@ -0,0 +1,83 @@
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from parameterized import parameterized
+
+from products.signals.backend.models import SignalReport
+from products.signals.backend.temporal.signal_queries import fetch_live_report_ids_for_source_ids
+
+VIEWS_FETCH = "products.signals.backend.views.fetch_live_report_ids_for_source_ids"
+VIEWS_FETCH_BY_PRODUCT = "products.signals.backend.views.fetch_report_ids_for_source_products"
+TICKET_ID = "019f9373-1e60-0000-3928-d8b21e6e8cb0"
+
+
+class TestLiveReportIdsForSourceIds(APIBaseTest):
+ def test_query_compiles_against_clickhouse(self) -> None:
+ # Regression guard for the alias-collision class documented on
+ # fetch_report_ids_for_source_ids: this query pushes the source_id filter into the shared
+ # dedup subquery (which exposes `metadata` as an argMax alias) and then filters an aliased
+ # `source_product` in an outer WHERE. If HogQL rejects either, the helper raises on every
+ # call and the caller degrades to "no linked reports" for everyone, silently. Run it for
+ # real against an empty ClickHouse: it must compile and return an empty map.
+ assert fetch_live_report_ids_for_source_ids(self.team, [TICKET_ID]) == {}
+ assert fetch_live_report_ids_for_source_ids(self.team, [TICKET_ID], "conversations") == {}
+
+ def test_no_source_ids_skips_clickhouse(self) -> None:
+ with patch("products.signals.backend.temporal.signal_queries.execute_hogql_query") as execute:
+ assert fetch_live_report_ids_for_source_ids(self.team, []) == {}
+ execute.assert_not_called()
+
+
+class TestReportsSourceIdFilter(APIBaseTest):
+ def _url(self, query: str) -> str:
+ return f"/api/projects/{self.team.pk}/signals/reports/?{query}"
+
+ def setUp(self) -> None:
+ super().setUp()
+ self.linked = SignalReport.objects.create(
+ team=self.team, status=SignalReport.Status.READY, title="linked to the ticket"
+ )
+ self.unlinked = SignalReport.objects.create(team=self.team, status=SignalReport.Status.READY, title="unrelated")
+
+ def test_filters_to_reports_the_source_record_contributed_to(self) -> None:
+ with (
+ patch(VIEWS_FETCH, return_value={TICKET_ID: [str(self.linked.id)]}) as fetch,
+ patch(VIEWS_FETCH_BY_PRODUCT) as fetch_by_product,
+ ):
+ response = self.client.get(self._url(f"source_id={TICKET_ID}&source_product=conversations"))
+
+ assert response.status_code == 200
+ assert [r["id"] for r in response.json()["results"]] == [str(self.linked.id)]
+ # A single source_product narrows the ClickHouse scan.
+ assert fetch.call_args.args[1:] == ([TICKET_ID], "conversations")
+ # ...and makes the wider source_product lookup redundant, so it must not also run.
+ fetch_by_product.assert_not_called()
+
+ @parameterized.expand(
+ [
+ ("no product at all", f"source_id={TICKET_ID}"),
+ ("several products", f"source_id={TICKET_ID}&source_product=conversations,zendesk"),
+ ]
+ )
+ def test_rejects_a_source_id_without_exactly_one_product(self, _name: str, query: str) -> None:
+ # A source id is only unique within a product (emitters pass through the external system's own
+ # id), so filtering without one would quietly mix products together.
+ with patch(VIEWS_FETCH) as fetch:
+ response = self.client.get(self._url(query))
+
+ assert response.status_code == 400
+ assert "source_product" in str(response.json())
+ fetch.assert_not_called()
+
+ def test_unknown_source_id_returns_nothing_rather_than_everything(self) -> None:
+ with patch(VIEWS_FETCH, return_value={}), patch(VIEWS_FETCH_BY_PRODUCT):
+ response = self.client.get(self._url("source_id=not-a-known-source&source_product=conversations"))
+
+ assert response.json()["results"] == []
+
+ def test_absent_filter_does_not_touch_clickhouse(self) -> None:
+ with patch(VIEWS_FETCH) as fetch:
+ response = self.client.get(self._url("limit=10"))
+
+ assert response.status_code == 200
+ fetch.assert_not_called()
diff --git a/products/signals/backend/test/test_support_writeback.py b/products/signals/backend/test/test_support_writeback.py
new file mode 100644
index 000000000000..87db5762839f
--- /dev/null
+++ b/products/signals/backend/test/test_support_writeback.py
@@ -0,0 +1,83 @@
+import uuid
+
+import pytest
+from posthog.test.base import BaseTest
+
+from posthog.models.comment import Comment
+
+from products.conversations.backend.models import Ticket
+from products.signals.backend.models import SignalReport
+from products.signals.backend.support_writeback import post_report_findings_to_tickets
+
+WRITEBACK_MODULE_PATH = "products.signals.backend.support_writeback"
+
+
+def _make_ticket(team):
+ return Ticket.objects.create_with_number(
+ team=team,
+ widget_session_id=str(uuid.uuid4()),
+ distinct_id="user-123",
+ channel_source="widget",
+ )
+
+
+def _ticket_notes(team, ticket):
+ return Comment.objects.filter(team=team, scope="conversations_ticket", item_id=str(ticket.id), deleted=False)
+
+
+class TestPostReportFindingsToTickets(BaseTest):
+ def setUp(self):
+ super().setUp()
+ self.ticket = _make_ticket(self.team)
+ self.report = SignalReport.objects.create(
+ team=self.team,
+ status=SignalReport.Status.READY,
+ title="fix(widget): stop dropping replies",
+ summary="The widget gates replies on a localStorage id.",
+ )
+ self.signal = {
+ "source_product": "conversations",
+ "source_id": str(self.ticket.id),
+ "content": "customer can't see replies",
+ }
+
+ def test_posts_a_private_note_pointing_at_the_report(self):
+ posted = post_report_findings_to_tickets(self.team, str(self.report.id), [self.signal])
+
+ assert posted == 1
+ note = _ticket_notes(self.team, self.ticket).get()
+ assert note.item_context["is_private"] is True
+ assert note.item_context["author_type"] == "AI"
+ assert f"/project/{self.team.pk}/inbox/{self.report.id}" in note.content
+
+ def test_note_carries_no_report_content(self):
+ # Comments authorize as `comment` while reports authorize as `task`, so a teammate with ticket
+ # access but no inbox access can read this note. It must not hand them the research itself.
+ post_report_findings_to_tickets(self.team, str(self.report.id), [self.signal])
+
+ content = _ticket_notes(self.team, self.ticket).get().content
+ assert self.report.title not in content
+ assert "localStorage id" not in content
+
+ def test_is_idempotent_across_retries(self):
+ first = post_report_findings_to_tickets(self.team, str(self.report.id), [self.signal])
+ second = post_report_findings_to_tickets(self.team, str(self.report.id), [self.signal])
+
+ assert (first, second) == (1, 0)
+ assert _ticket_notes(self.team, self.ticket).count() == 1
+
+ def test_ignores_signals_from_other_products(self):
+ error_signal = {"source_product": "error_tracking", "source_id": "issue-1"}
+
+ posted = post_report_findings_to_tickets(self.team, str(self.report.id), [error_signal])
+
+ assert posted == 0
+ assert not Comment.objects.filter(team=self.team, scope="conversations_ticket").exists()
+
+ def test_does_not_leak_across_teams(self):
+ other_team_signal = {"source_product": "conversations", "source_id": str(uuid.uuid4())}
+
+ posted = post_report_findings_to_tickets(self.team, str(self.report.id), [other_team_signal])
+
+ assert posted == 0
diff --git a/products/signals/backend/views.py b/products/signals/backend/views.py
index b143d02a27e4..3f9d71dd8b5c 100644
--- a/products/signals/backend/views.py
+++ b/products/signals/backend/views.py
@@ -140,6 +140,7 @@ from products.signals.backend.temporal.deletion import SignalReportDeletionWorkf
from products.signals.backend.temporal.grouping_v2 import TeamSignalGroupingV2Workflow
from products.signals.backend.temporal.reingestion import SignalReportReingestionWorkflow
from products.signals.backend.temporal.signal_queries import (
+ fetch_live_report_ids_for_source_ids,
fetch_report_ids_for_scout_names,
fetch_report_ids_for_source_products,
fetch_signals_for_report_sync,
@@ -723,6 +724,7 @@ class SignalReportViewSet(
qs = self._apply_signal_report_status_filter(qs)
qs = self._apply_signal_report_search_filter(qs)
qs = self._apply_signal_report_source_product_filter(qs)
+ qs = self._apply_signal_report_source_id_filter(qs)
qs = self._apply_signal_report_scout_filter(qs)
qs = self._apply_signal_report_implementation_pr_filter(qs)
qs = self._apply_signal_report_suggested_reviewer_filter(qs)
@@ -838,6 +840,10 @@ class SignalReportViewSet(
source_product_filter = self.request.query_params.get("source_product")
if not source_product_filter:
return queryset
+ # `source_id` already implies its product, so its narrower lookup subsumes this one. Skip
+ # rather than run a second ClickHouse query for a strictly wider set.
+ if self.request.query_params.get("source_id"):
+ return queryset
source_products = [s.strip() for s in source_product_filter.split(",") if s.strip()]
if not source_products:
@@ -846,6 +852,37 @@ class SignalReportViewSet(
report_ids_with_source = fetch_report_ids_for_source_products(self.team, source_products)
return queryset.filter(id__in=report_ids_with_source)
+ def _apply_signal_report_source_id_filter(self, queryset):
+ """Reports a specific source record contributed to, e.g. one support ticket's reports.
+
+ The owning product asks with the id it already has, instead of reaching into signals.
+
+ Requires a single `source_product`, because a source id is only unique within one: emitters
+ pass through the external system's own id, so GitHub issue 42 and Jira issue 42 both arrive as
+ `"42"`. `SignalEmissionRecord` says the same thing with its `(team, source_product, source_type,
+ source_id)` constraint. Without the product this would quietly mix products together.
+ """
+ source_id_filter = self.request.query_params.get("source_id")
+ if not source_id_filter:
+ return queryset
+
+ source_ids = [s.strip() for s in source_id_filter.split(",") if s.strip()]
+ if not source_ids:
+ return queryset
+
+ source_product = self.request.query_params.get("source_product")
+ product = source_product.strip() if source_product else ""
+ if not product or "," in product:
+ raise exceptions.ValidationError(
+ {
+ "source_id": "Pass exactly one source_product alongside source_id. A source id is only "
+ "unique within its product, so filtering without one would mix products together."
+ }
+ )
+ by_source = fetch_live_report_ids_for_source_ids(self.team, source_ids, product)
+ report_ids = {report_id for ids in by_source.values() for report_id in ids}
+ return queryset.filter(id__in=report_ids)
+
def _apply_signal_report_scout_filter(self, queryset):
scout_filter = self.request.query_params.get("scout")
if not scout_filter:
@@ -1315,6 +1352,18 @@ class SignalReportViewSet(
"their contributing signals comes from one of these products (e.g. error_tracking, session_replay)."
),
),
+ OpenApiParameter(
+ name="source_id",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description=(
+ "Comma-separated list of source record ids. Reports are kept if at least one of their "
+ "contributing signals came from one of these records — e.g. pass a support ticket's UUID to "
+ "see what the inbox already found for that ticket. Requires exactly one source_product, "
+ "since a source id is only unique within its product."
+ ),
+ ),
OpenApiParameter(
name="scout",
type=OpenApiTypes.STR,
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index 6f9f2df17005..3db75e0d08e5 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -3470,6 +3470,10 @@ export type SignalsReportsListParams = {
* Case-insensitive substring match against report title and summary.
*/
search?: string
+ /**
+ * Comma-separated list of source record ids. Reports are kept if at least one of their contributing signals came from one of these records — e.g. pass a support ticket's UUID to see what the inbox already found for that ticket. Requires exactly one source_product, since a source id is only unique within its product.
+ */
+ source_id?: string
/**
* Comma-separated list of source products to include. Reports are kept if at least one of their contributing signals comes from one of these products (e.g. error_tracking, session_replay).
*/
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index bf7b80705ce4..4343d5c3c951 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -79581,6 +79581,10 @@ export namespace Schemas {
* Case-insensitive substring match against report title and summary.
*/
search?: string;
+ /**
+ * Comma-separated list of source record ids. Reports are kept if at least one of their contributing signals came from one of these records — e.g. pass a support ticket's UUID to see what the inbox already found for that ticket. Requires exactly one source_product, since a source id is only unique within its product.
+ */
+ source_id?: string;
/**
* Comma-separated list of source products to include. Reports are kept if at least one of their contributing signals comes from one of these products (e.g. error_tracking, session_replay).
*/
diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.ts
index 7d9ec027b7cf..9cc97b4e2b34 100644
--- a/services/mcp/src/generated/signals/api.ts
+++ b/services/mcp/src/generated/signals/api.ts
@@ -50,6 +50,12 @@ export const SignalsReportsListQueryParams = /* @__PURE__ */ zod.object({
'Comma-separated list of scout skill_name slugs (e.g. signals-scout-error-tracking). Reports are kept if at least one of their contributing signals was authored by one of these scouts. Combines with source_product as an AND.'
),
search: zod.string().optional().describe('Case-insensitive substring match against report title and summary.'),
+ source_id: zod
+ .string()
+ .optional()
+ .describe(
+ "Comma-separated list of source record ids. Reports are kept if at least one of their contributing signals came from one of these records — e.g. pass a support ticket's UUID to see what the inbox already found for that ticket. Requires exactly one source_product, since a source id is only unique within its product."
+ ),
source_product: zod
.string()
.optional()
diff --git a/services/mcp/src/tools/generated/signals.ts b/services/mcp/src/tools/generated/signals.ts
index 91d28df1f609..b427fc9223b1 100644
--- a/services/mcp/src/tools/generated/signals.ts
+++ b/services/mcp/src/tools/generated/signals.ts
@@ -235,6 +235,7 @@ const inboxReportsList = (): ToolBase<
priority: params.priority,
scout: params.scout,
search: params.search,
+ source_id: params.source_id,
source_product: params.source_product,
status: params.status,
suggested_reviewers: params.suggested_reviewers,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-reports-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-reports-list.json
index 79553e205be7..062de0cf0cf4 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-reports-list.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-reports-list.json
@@ -33,6 +33,10 @@
"description": "Case-insensitive substring match against report title and summary.",
"type": "string"
},
+ "source_id": {
+ "description": "Comma-separated list of source record ids. Reports are kept if at least one of their contributing signals came from one of these records — e.g. pass a support ticket's UUID to see what the inbox already found for that ticket. Requires exactly one source_product, since a source id is only unique within its product.",
+ "type": "string"
+ },
"source_product": {
"description": "Comma-separated list of source products to include. Reports are kept if at least one of their contributing signals comes from one of these products (e.g. error_tracking, session_replay).",
"type": "string"