:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(inbox): Replace report Feedback button with Discuss (#68272)
Michael Matloka4f76d969a679
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 70b4c90fbe5b..eb0bdae5b2f3 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -254,8 +254,8 @@ import type {SessionSummariesConfig,} from 'products/session_summaries/frontend/types'import type {- ClaudeTaskRunCreateSchemaApi,TaskRunBootstrapCreateRequestInitialPermissionModeEnumApi,+ TaskRunCreateRequestSchemaApi,} from 'products/tasks/frontend/generated/api.schemas'import type { BlastRadiusApi } from 'products/workflows/frontend/generated/api.schemas'import type { OptOutEntry } from 'products/workflows/frontend/OptOuts/types'@@ -5342,7 +5342,7 @@ const api = {async bulkReorder(columns: Record<string, string[]>): Promise<{ updated: number; tasks: Task[] }> {return await new ApiRequest().tasks().withAction('bulk_reorder').create({ data: { columns } })},- async run(id: Task['id'], data?: ClaudeTaskRunCreateSchemaApi): Promise<Task> {+ async run(id: Task['id'], data?: TaskRunCreateRequestSchemaApi): Promise<Task> {return await new ApiRequest().task(id).withAction('run')diff --git a/frontend/src/scenes/inbox/components/detail/DiscussReportButton.tsx b/frontend/src/scenes/inbox/components/detail/DiscussReportButton.tsxnew file mode 100644index 000000000000..55c574f35edd--- /dev/null+++ b/frontend/src/scenes/inbox/components/detail/DiscussReportButton.tsx@@ -0,0 +1,78 @@+import { useActions, useValues } from 'kea'+import { useState } from 'react'++import { IconMessage } from '@posthog/icons'+import { LemonButton } from '@posthog/lemon-ui'++import { LemonTextArea } from 'lib/lemon-ui/LemonTextArea'+import { Popover } from 'lib/lemon-ui/Popover'++import { captureInboxReportAction } from '../../inboxAnalytics'+import { inboxTaskKickoffLogic } from '../../inboxTaskKickoffLogic'+import { SignalReport } from '../../types'++/**+ * Discuss opens a small popover with a textarea so the user poses their question up front, then kicks+ * off a fresh research task whose prompt is the report link (for the agent to open and read) followed+ * by that question. Discuss never changes the report's state, so it stays available for every report –+ * including resolved and archived ones.+ */+export function DiscussReportButton({ report, reportUrl }: { report: SignalReport; reportUrl: string }): JSX.Element {+ const { isDiscussing } = useValues(inboxTaskKickoffLogic)+ const { discussReport } = useActions(inboxTaskKickoffLogic)+ const [isOpen, setIsOpen] = useState(false)+ const [question, setQuestion] = useState('')++ const submit = (): void => {+ const trimmed = question.trim()+ if (!trimmed) {+ return+ }+ captureInboxReportAction({ report, actionType: 'discuss', surface: 'detail_pane' })+ discussReport(report, reportUrl, trimmed)+ setIsOpen(false)+ setQuestion('')+ }++ return (+ <Popover+ visible={isOpen}+ onClickOutside={() => setIsOpen(false)}+ placement="bottom-end"+ overlay={+ <div className="flex flex-col gap-2 p-2 w-[22rem]">+ <LemonTextArea+ value={question}+ onChange={setQuestion}+ onPressEnter={submit}+ placeholder="What would you like to discuss about this report?"+ maxLength={4000}+ rows={4}+ autoFocus+ />+ <div className="flex justify-end">+ <LemonButton+ type="primary"+ size="small"+ onClick={submit}+ loading={isDiscussing}+ disabledReason={question.trim() ? undefined : 'Enter a question first'}+ >+ Discuss+ </LemonButton>+ </div>+ </div>+ }+ >+ <LemonButton+ type="secondary"+ size="small"+ icon={<IconMessage />}+ onClick={() => setIsOpen((open) => !open)}+ tooltip="Ask an agent about this report"+ >+ Discuss+ </LemonButton>+ </Popover>+ )+}diff --git a/frontend/src/scenes/inbox/components/detail/ReportDetail.tsx b/frontend/src/scenes/inbox/components/detail/ReportDetail.tsxindex c2bb32c7a357..3f15222d9c5b 100644--- a/frontend/src/scenes/inbox/components/detail/ReportDetail.tsx+++ b/frontend/src/scenes/inbox/components/detail/ReportDetail.tsx@@ -36,6 +36,7 @@ import {import { ConventionalCommitScopeTag } from '../cards/ReportCard'import { CommitContent } from './artefactTypes'import { DetailSection } from './DetailSection'+import { DiscussReportButton } from './DiscussReportButton'import { PullRequestBranchTag, PullRequestDiffPanel } from './PullRequestDiffPanel'import { ReportActivitySection } from './ReportActivitySection'import { ReportDetailAction, useReportDetailActions } from './ReportDetailActions'@@ -286,7 +287,9 @@ export function InboxDetailFrame({const conventionalTitle = parseConventionalCommitTitle(report.title)const displayTitle = displayConventionalCommitTitle(report.title, 'Untitled report')- const reportPath = urls.inboxReport(tab, report.id)+ // Absolute URL to this report – used for the copy-link action and seeded into the Discuss prompt+ // so the agent can open and read the report directly.+ const reportUrl = `${window.location.origin}${addProjectIdIfMissing(urls.inboxReport(tab, report.id))}`// Secondary actions as data so the same set renders inline as buttons on wide layouts and as a// standard `LemonMenu` on narrow ones; the primary action stays inline either way.@@ -297,8 +300,7 @@ export function InboxDetailFrame({label: 'Copy link',icon: <IconLink />,tooltip: 'Copy a link to this report',- onClick: () =>- void copyToClipboard(`${window.location.origin}${addProjectIdIfMissing(reportPath)}`, 'report link'),+ onClick: () => void copyToClipboard(reportUrl, 'report link'),},...detailActions,]@@ -405,6 +407,8 @@ export function InboxDetailFrame({</div><div className="flex items-center gap-2 @2xl:shrink-0">{primaryAction}+ {/* Discuss is always available and stays inline as its own dropdown button. */}+ <DiscussReportButton report={report} reportUrl={reportUrl} />{/* Buttons inline on wide layouts; collapse into a standard LemonMenu kebab below @4xl. */}<div className="hidden @4xl:flex items-center gap-2">{reportActions.map((action) => (diff --git a/frontend/src/scenes/inbox/components/detail/ReportDetailActions.tsx b/frontend/src/scenes/inbox/components/detail/ReportDetailActions.tsxindex d64f604f8114..4f7ee5d695e1 100644--- a/frontend/src/scenes/inbox/components/detail/ReportDetailActions.tsx+++ b/frontend/src/scenes/inbox/components/detail/ReportDetailActions.tsx@@ -2,13 +2,13 @@ import { useActions, useValues } from 'kea'import { router } from 'kea-router'import { type MouseEvent, useState } from 'react'-import { IconArchive, IconMessage, IconPullRequest, IconReceipt, IconUndo } from '@posthog/icons'+import { IconArchive, IconPullRequest, IconReceipt, IconUndo } from '@posthog/icons'import { lemonToast } from '@posthog/lemon-ui'import api from 'lib/api'import { urls } from 'scenes/urls'-import { captureInboxReportAction, captureInboxReportFeedback } from '../../inboxAnalytics'+import { captureInboxReportAction } from '../../inboxAnalytics'import { inboxSceneLogic } from '../../inboxSceneLogic'import { inboxTaskKickoffLogic } from '../../inboxTaskKickoffLogic'import { inboxBulkActionsLogic } from '../../logics/inboxBulkActionsLogic'@@ -16,7 +16,6 @@ import { INBOX_FLAT_TAB_LIST_PARAMS, reportListLogic } from '../../logics/reportimport { ACTIONABLE_ACTIONABILITY_VALUES, SignalReport, SignalReportStatus } from '../../types'import { useReportArchive } from '../cards/useReportArchive'import { useReportRefund } from '../cards/useReportRefund'-import { openFeedbackReportDialog } from '../shell/FeedbackReportDialog'/*** One detail-pane action, rendered either inline as a `LemonButton` (wide layouts) or as a@@ -55,8 +54,9 @@ function canCreateImplementationPr(report: SignalReport): boolean {}/**- * Detail-pane actions as data: Feedback (always), Archive/Restore, and Create PR. Task- * creation/navigation is owned by `inboxTaskKickoffLogic`; archiving reuses the shared+ * Detail-pane actions as data: Archive/Restore and Create PR. Discuss is rendered separately as a+ * standalone dropdown button (`DiscussReportButton`) since it opens a question popover rather than+ * firing on click. Task creation is owned by `inboxTaskKickoffLogic`; archiving reuses the shared* `useReportArchive` dialog flow. Callers render these inline or inside a menu.*/export function useReportDetailActions(report: SignalReport): ReportDetailAction[] {@@ -139,27 +139,11 @@ export function useReportDetailActions(report: SignalReport): ReportDetailAction}}- // Feedback is always available – it never changes the report's state, just records what the- // user thinks of it (and its PR), so it stays even for resolved/archived reports.- const feedback: ReportDetailAction = {- key: 'feedback',- label: 'Feedback',- icon: <IconMessage />,- tooltip: 'Tell us how useful this report was',- onClick: () =>- openFeedbackReportDialog({- reportTitle: report.title ?? 'Untitled report',- onConfirm: ({ sentiment, note }) => {- captureInboxReportFeedback({ report, sentiment, note, surface: 'detail_pane' })- lemonToast.success('Thanks for the feedback')- },- }),- }-- // A resolved report is terminal – its PR already merged, so only feedback applies. The PR can- // still be refunded (auto-approved by design; the weekly review watches refunded-then-merged).+ // A resolved report is terminal – its PR already merged, so only Discuss (rendered separately)+ // and Refund apply. The PR can still be refunded (auto-approved by design; the weekly review+ // watches refunded-then-merged).if (isResolved) {- return [feedback, ...(canRefund ? [refund] : [])]+ return canRefund ? [refund] : []}// An already-archived report offers Restore instead of Archive (and no Create PR). A refunded@@ -167,7 +151,6 @@ export function useReportDetailActions(report: SignalReport): ReportDetailAction// archived-but-still-charged report can still be refunded.if (isArchived) {return [- feedback,...(canRefund ? [refund] : []),...(report.refund? []@@ -185,7 +168,6 @@ export function useReportDetailActions(report: SignalReport): ReportDetailAction}const actions: ReportDetailAction[] = [- feedback,{key: 'archive',label: 'Archive',diff --git a/frontend/src/scenes/inbox/components/shell/FeedbackReportDialog.tsx b/frontend/src/scenes/inbox/components/shell/FeedbackReportDialog.tsxdeleted file mode 100644index 8f70a0e48574..000000000000--- a/frontend/src/scenes/inbox/components/shell/FeedbackReportDialog.tsx+++ /dev/null@@ -1,88 +0,0 @@-import { IconThumbsDown, IconThumbsUp } from '@posthog/icons'--import { LemonDialog } from 'lib/lemon-ui/LemonDialog'-import { LemonField } from 'lib/lemon-ui/LemonField'-import { LemonRadio, LemonRadioOption } from 'lib/lemon-ui/LemonRadio'-import { LemonTextArea } from 'lib/lemon-ui/LemonTextArea'--import { InboxReportFeedbackSentiment } from '../../inboxAnalytics'--/** Generous cap — feedback notes can be a paragraph or two of detail about a report or its PR. */-const FEEDBACK_NOTE_MAX_LENGTH = 10000--export interface FeedbackReportDialogResult {- sentiment: InboxReportFeedbackSentiment- note: string-}--interface OpenFeedbackReportDialogParams {- /** Report title for the dialog copy. */- reportTitle?: string | null- /** Called with the chosen sentiment + note once the user submits. */- onConfirm: (result: FeedbackReportDialogResult) => void | Promise<void>-}--const SENTIMENT_RADIO_OPTIONS: LemonRadioOption<InboxReportFeedbackSentiment>[] = [- {- value: 'positive',- label: (- <span className="inline-flex items-center gap-1.5">- <IconThumbsUp className="shrink-0 text-success" />- Helpful- </span>- ),- },- {- value: 'negative',- label: (- <span className="inline-flex items-center gap-1.5">- <IconThumbsDown className="shrink-0 text-danger" />- Not helpful- </span>- ),- },-]--/**- * Opens the report feedback dialog: pick a thumbs sentiment plus an optional note, then submit.- * Feedback-only — the report stays in the inbox (unlike {@link openDismissReportDialog}). The- * caller wires `onConfirm` to fire the `Inbox report feedback` analytics event.- */-export function openFeedbackReportDialog({ reportTitle, onConfirm }: OpenFeedbackReportDialogParams): void {- LemonDialog.openForm({- title: `Feedback on "${reportTitle?.trim() ? reportTitle : 'Untitled report'}"`,- description:- 'Tell us how useful this report was. Your feedback helps the agent improve – it does not archive the report.',- maxWidth: '30rem',- initialValues: { sentiment: null as InboxReportFeedbackSentiment | null, note: '' },- content: (- <div className="flex flex-col gap-3">- <LemonField name="sentiment" label="How useful was this?">- {({ value, onChange }) => (- <LemonRadio value={value} onChange={onChange} options={SENTIMENT_RADIO_OPTIONS} />- )}- </LemonField>- <LemonField name="note" label="Anything to add?" info="Optional – helps the agent learn">- <LemonTextArea- placeholder="Optional: what was useful or off?"- maxLength={FEEDBACK_NOTE_MAX_LENGTH}- rows={4}- // Keep Enter for newlines – without this it bubbles to the dialog's submit-on-Enter handler.- stopPropagation- />- </LemonField>- </div>- ),- errors: {- sentiment: (sentiment) => (!sentiment ? "You haven't picked a rating" : undefined),- },- primaryButtonProps: { children: 'Send feedback' },- shouldAwaitSubmit: true,- onSubmit: async ({ sentiment, note }) => {- if (!sentiment) {- return- }- await onConfirm({ sentiment, note: (note ?? '').trim() })- },- })-}diff --git a/frontend/src/scenes/inbox/inboxAnalytics.ts b/frontend/src/scenes/inbox/inboxAnalytics.tsindex 17ce27f560b1..f6e10f01a5ea 100644--- a/frontend/src/scenes/inbox/inboxAnalytics.ts+++ b/frontend/src/scenes/inbox/inboxAnalytics.ts@@ -17,7 +17,6 @@ export const INBOX_EVENTS = {REPORT_OPENED: 'Inbox report opened',REPORT_CLOSED: 'Inbox report closed',REPORT_ACTION: 'Inbox report action',- REPORT_FEEDBACK: 'Inbox report feedback',SOURCE_CONNECTED: 'Signal source connected',SOURCE_INTEREST: 'signals source interest',} as const@@ -33,9 +32,6 @@ export type InboxReportOpenMethod = 'click' | 'deeplink' | 'unknown'/** How a report detail was closed. */export type InboxReportCloseMethod = 'next_report' | 'deselected' | 'unmount'-/** Sentiment captured by the report feedback button. */-export type InboxReportFeedbackSentiment = 'positive' | 'negative'-/*** Report actions cloud actually emits. Names match the desktop enum one-for-one (so the* `action_type` breakdown reads the same across clients), plus a cloud-only `restore` for the@@ -43,6 +39,7 @@ export type InboxReportFeedbackSentiment = 'positive' | 'negative'*/export type InboxReportActionType =| 'dismiss'+ | 'discuss'| 'restore'| 'create_pr'| 'refund'@@ -72,8 +69,8 @@ interface BaseReportProperties {/*** Identity + classification for a report. Kept to opaque ids, enums, ages, and counts — it never* includes the agent-generated report title, which can echo proprietary detail from a customer's- * own data. User-authored notes (a dismissal reason note, feedback note) are a different case: they- * are the actionable signal we want, so the relevant capture calls attach them explicitly.+ * own data. A user-authored dismissal reason note is a different case: it is the actionable signal+ * we want, so the relevant capture call attaches it explicitly.*/function baseReportProperties(report: SignalReport): BaseReportProperties {return {@@ -191,26 +188,6 @@ export function captureInboxReportAction(params: {})}-/**- * Free-form feedback on a single report, fired from the detail pane's feedback button. Unlike a- * dismiss, this is feedback-only: the report stays in the inbox. Carries the thumbs sentiment plus- * the optional note text so we can read what people actually think of a report (and its PR).- */-export function captureInboxReportFeedback(params: {- report: SignalReport- sentiment: InboxReportFeedbackSentiment- note: string- surface: InboxReportActionSurface-}): void {- captureInboxEvent(INBOX_EVENTS.REPORT_FEEDBACK, {- ...baseReportProperties(params.report),- sentiment: params.sentiment,- has_pr: !!params.report.implementation_pr_url,- ...(params.note ? { note: params.note } : {}),- surface: params.surface,- })-}-export function captureSignalSourceConnected(params: {sourceProduct: stringsourceType: stringdiff --git a/frontend/src/scenes/inbox/inboxTaskKickoffLogic.ts b/frontend/src/scenes/inbox/inboxTaskKickoffLogic.tsindex a07e3b118e57..da181727d296 100644--- a/frontend/src/scenes/inbox/inboxTaskKickoffLogic.ts+++ b/frontend/src/scenes/inbox/inboxTaskKickoffLogic.ts@@ -7,9 +7,15 @@ import api from 'lib/api'import { urls } from 'scenes/urls'import { OriginProduct } from 'products/posthog_ai/frontend/types/taskTypes'+import { RunSourceEnumApi } from 'products/tasks/frontend/generated/api.schemas'import type { inboxTaskKickoffLogicType } from './inboxTaskKickoffLogicType'-import { SIGNAL_REPORT_TASK_IMPLEMENTATION_RELATIONSHIP, SignalReport, SignalReportTaskRelationship } from './types'+import {+ SIGNAL_REPORT_TASK_DISCUSSION_RELATIONSHIP,+ SIGNAL_REPORT_TASK_IMPLEMENTATION_RELATIONSHIP,+ SignalReport,+ SignalReportTaskRelationship,+} from './types'// Cloud-adapted port of desktop `useDiscussReport` / `useCreatePrReport`. These are// task-kickoff actions (create a cloud Task linked to the report, then navigate to it) –@@ -32,15 +38,10 @@ function buildCreatePrReportPrompt(report: SignalReport, feedback?: string): strreturn `${base}\n\nAdditional feedback from the user (take this into account):\n${trimmed}`}-function buildDiscussReportPrompt(report: SignalReport, question?: string): string {- const base = `Discuss PostHog Inbox report "${report.title ?? report.id}" (id ${report.id}). Investigate the contributing findings and help the user understand and decide what to do.${- report.summary ? `\n\nReport summary:\n${report.summary}` : ''- }`- const trimmed = question?.trim()- if (!trimmed) {- return base- }- return `${base}\n\nThe user asks:\n${trimmed}`+function buildDiscussReportPrompt(reportUrl: string, question: string): string {+ // The task is already linked to the report, but including the URL lets the agent open and read+ // the full report itself. The user's question follows after a blank line for clear separation.+ return `Let's discuss this PostHog Inbox report: ${reportUrl}\n\n${question.trim()}`}async function createReportTask(@@ -87,6 +88,14 @@ async function createReportTask(signal_report_task_relationship: relationship,} as Parameters<typeof api.tasks.create>[0])+ // Kick off a cloud run so the task actually executes — creating it alone lands the user on a+ // "This task hasn't been run yet" screen. `run_source` ties the run to the report and makes any+ // PR bot-authored server-side, mirroring the auto-start pipeline's `create_and_run_task`.+ await api.tasks.run(task.id, {+ run_source: RunSourceEnumApi.SignalReport,+ signal_report_id: report.id,+ })+router.actions.push(urls.taskDetail(task.id))}@@ -94,7 +103,7 @@ export const inboxTaskKickoffLogic = kea<inboxTaskKickoffLogicType>([path(['scenes', 'inbox', 'inboxTaskKickoffLogic']),actions({- discussReport: (report: SignalReport, question?: string) => ({ report, question }),+ discussReport: (report: SignalReport, reportUrl: string, question: string) => ({ report, reportUrl, question }),createPrFromReport: (report: SignalReport) => ({ report }),discussReportSuccess: true,discussReportFailure: true,@@ -122,9 +131,14 @@ export const inboxTaskKickoffLogic = kea<inboxTaskKickoffLogicType>([}),listeners(({ actions }) => ({- discussReport: async ({ report, question }) => {+ discussReport: async ({ report, reportUrl, question }) => {try {- await createReportTask(report, 'research', buildDiscussReportPrompt(report, question), 'Discuss report')+ await createReportTask(+ report,+ SIGNAL_REPORT_TASK_DISCUSSION_RELATIONSHIP,+ buildDiscussReportPrompt(reportUrl, question),+ 'Discuss report'+ )actions.discussReportSuccess()} catch (error: any) {lemonToast.error(error?.detail || error?.message || 'Failed to start discussion')diff --git a/frontend/src/scenes/inbox/types.ts b/frontend/src/scenes/inbox/types.tsindex 617127e8a332..4f297787425b 100644--- a/frontend/src/scenes/inbox/types.ts+++ b/frontend/src/scenes/inbox/types.ts@@ -210,15 +210,19 @@ export const INBOX_SCOPE_ENTIRE_PROJECT: InboxScope = 'entire-project'// ── SignalReport ↔ Task linkage ─────────────────────────────────────────────// The task↔report association is the `task_run` artefact log (see artefactTypes.ts). The-// relationship vocabulary below is retained only for the task-creation kickoff path, where the-// backend still accepts `signal_report_task_relationship` (implementation) when starting a PR run.+// relationship vocabulary below is what a client may assert on the task-creation kickoff path via+// `signal_report_task_relationship`: `implementation` starts a PR run (and opens the auto-start+// spend gate), `discussion` links a discuss-the-report task. `research` is reserved for the+// server-side research pipeline and is rejected by the tasks API.-export const SIGNAL_REPORT_TASK_RELATIONSHIPS = ['repo_selection', 'research', 'implementation'] as const+export const SIGNAL_REPORT_TASK_RELATIONSHIPS = ['implementation', 'discussion'] as constexport type SignalReportTaskRelationship = (typeof SIGNAL_REPORT_TASK_RELATIONSHIPS)[number]export const SIGNAL_REPORT_TASK_IMPLEMENTATION_RELATIONSHIP: SignalReportTaskRelationship = 'implementation'+export const SIGNAL_REPORT_TASK_DISCUSSION_RELATIONSHIP: SignalReportTaskRelationship = 'discussion'+// ── Autonomy config (per-user override; backend SignalUserAutonomyConfigView) ─export interface SignalUserAutonomyConfig {diff --git a/products/signals/backend/artefact_schemas.py b/products/signals/backend/artefact_schemas.pyindex bf3baafe7b55..e226d00a091a 100644--- a/products/signals/backend/artefact_schemas.py+++ b/products/signals/backend/artefact_schemas.py@@ -360,6 +360,8 @@ SIGNALS_PRODUCT = "signals"TASK_RUN_TYPE_REPO_SELECTION = "repo_selection"TASK_RUN_TYPE_RESEARCH = "research"TASK_RUN_TYPE_IMPLEMENTATION = "implementation"+# A discuss-the-report task started by a user from the Inbox (not the automated research run).+TASK_RUN_TYPE_DISCUSSION = "discussion"# Generic identifiers for a legacy `SignalReportTask` row with no `(product, type)` label — an# unlabelled link from the brief link-only window before associations carried identifiers.@@ -367,7 +369,12 @@ _LEGACY_TASK_RUN_PRODUCT = "tasks"_LEGACY_TASK_RUN_TYPE = "agent_run"_SIGNALS_TASK_RUN_TYPES = frozenset(- {TASK_RUN_TYPE_REPO_SELECTION, TASK_RUN_TYPE_RESEARCH, TASK_RUN_TYPE_IMPLEMENTATION}+ {+ TASK_RUN_TYPE_REPO_SELECTION,+ TASK_RUN_TYPE_RESEARCH,+ TASK_RUN_TYPE_IMPLEMENTATION,+ TASK_RUN_TYPE_DISCUSSION,+ })diff --git a/products/signals/backend/task_run_artefacts.py b/products/signals/backend/task_run_artefacts.pyindex 31d68089241f..5930553a0cef 100644--- a/products/signals/backend/task_run_artefacts.py+++ b/products/signals/backend/task_run_artefacts.py@@ -15,6 +15,7 @@ from __future__ import annotationsfrom products.signals.backend.artefact_schemas import (SIGNALS_PRODUCT,+ TASK_RUN_TYPE_DISCUSSION,TASK_RUN_TYPE_IMPLEMENTATION,TASK_RUN_TYPE_REPO_SELECTION,TASK_RUN_TYPE_RESEARCH,@@ -28,12 +29,14 @@ from products.signals.backend.models import ArtefactAttribution, SignalReport, S# working.__all__ = ["SIGNALS_PRODUCT",+ "TASK_RUN_TYPE_DISCUSSION","TASK_RUN_TYPE_IMPLEMENTATION","TASK_RUN_TYPE_REPO_SELECTION","TASK_RUN_TYPE_RESEARCH","aappend_task_run_artefact","append_task_run_artefact","record_implementation_task",+ "record_report_task","signals_task_ids",]@@ -130,3 +133,25 @@ def record_implementation_task(task_id=task_id,run_id=run_id,)+++def record_report_task(+ *, team_id: int, report_id: str, task_id: str, relationship: str | None = None, run_id: str | None = None+) -> SignalReportArtefact:+ """Record a task↔report association a client asserted when creating a task from the report.++ `implementation` (also the default when no relationship is given) additionally writes the legacy+ `SignalReportTask` gate row that guards auto-start spend, via `record_implementation_task`. Every+ other relationship records only the `task_run` work-log artefact under `product="signals"`+ (`research` never reaches here — it is created solely by the server-side research pipeline).+ """+ if relationship is None or relationship == TASK_RUN_TYPE_IMPLEMENTATION:+ return record_implementation_task(team_id=team_id, report_id=report_id, task_id=task_id, run_id=run_id)+ return append_task_run_artefact(+ team_id=team_id,+ report_id=report_id,+ product=SIGNALS_PRODUCT,+ type=relationship,+ task_id=task_id,+ run_id=run_id,+ )diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex de9129563ca6..b0b9816812bf 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -3439,7 +3439,7 @@ def create_task(team_id: int, user_id: int | None, *, validated_data: dict) -> cfrom posthog.models import Team # noqa: PLC0415from products.signals.backend.task_run_artefacts import ( # noqa: PLC0415 — cross-product write kept off the api import path- record_implementation_task,+ record_report_task,)from products.tasks.backend.logic.services.title_generator import generate_task_title # noqa: PLC0415from products.tasks.backend.temporal.process_task.utils import ( # noqa: PLC0415 — keep temporalio off the api import path@@ -3518,9 +3518,9 @@ def create_task(team_id: int, user_id: int | None, *, validated_data: dict) -> c)return _task_detail_to_dto(_task_detail_queryset().get(pk=warm_task.pk))- # Only IMPLEMENTATION is accepted; pop it so it isn't forwarded to the model. The link itself- # is recorded by record_implementation_task below.- validated_data.pop("signal_report_task_relationship", None)+ # The relationship the client asserted (validated by the serializer, which rejects `research`).+ # Popped so it isn't forwarded to the model; the link itself is recorded by record_report_task below.+ signal_report_task_relationship = validated_data.pop("signal_report_task_relationship", None)if not validated_data.get("github_integration"):default_integration = Integration.objects.filter(team=team, kind="github").first()@@ -3554,12 +3554,14 @@ def create_task(team_id: int, user_id: int | None, *, validated_data: dict) -> cwith transaction.atomic():task = Task.objects.create(**validated_data)if task.signal_report_id and task.origin_product == Task.OriginProduct.SIGNAL_REPORT:- # Dual-write the implementation gate row + task_run work-log artefact (see- # record_implementation_task) so a manually-started task matches autostarted ones.- record_implementation_task(+ # Record the task↔report association + work-log artefact for the asserted relationship+ # (defaults to implementation, which also writes the auto-start spend gate row) so a+ # manually-started task matches autostarted ones.+ record_report_task(team_id=task.team_id,report_id=str(task.signal_report_id),task_id=str(task.id),+ relationship=signal_report_task_relationship,)return _task_detail_to_dto(_task_detail_queryset().get(pk=task.pk))diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.pyindex bd992b56cf0d..91d58f1f8f96 100644--- a/products/tasks/backend/presentation/serializers.py+++ b/products/tasks/backend/presentation/serializers.py@@ -1,3 +1,4 @@+import reimport jsonimport base64import logging@@ -307,11 +308,15 @@ class TaskRunDetailSerializer(DataclassSerializer):]-# Only implementation is supported when linking a task to a report from the public task API-# (e.g. PostHog Code inbox); research/repo-selection links are created by server-side flows.-# Mirrors `signals` `task_run_artefacts.TASK_RUN_TYPE_IMPLEMENTATION` — kept inline-# so presentation never imports the other product's internals.-SIGNAL_REPORT_TASK_RELATIONSHIP_IMPLEMENTATION = "implementation"+# The relationship a client asserts between a task and a signal report when creating a task from the+# report (e.g. PostHog Code inbox), recorded as a signals `task_run` work-log entry. This is a+# free-form label — the same as the `task_run` artefact `(product, type)` values, which have never+# been access-controlled — so no relationship is reserved here either. `implementation` additionally+# opens the auto-start spend gate (recorded server-side via `record_report_task`). Only the routing-+# safe format is enforced, so a malformed value returns 400 rather than 500 from the artefact schema.+# Mirrors the routing-safe identifier rule in `signals` `artefact_schemas` (_IDENTIFIER_PART_RE),+# kept inline so presentation never imports the other product's internals.+_SIGNAL_REPORT_TASK_RELATIONSHIP_RE = re.compile(r"^[a-z0-9][a-z0-9_-]*$")class TaskSerializer(DataclassSerializer):@@ -409,11 +414,17 @@ class TaskWriteSerializer(serializers.Serializer):allow_null=True,help_text="Signal report this task implements, when created from a report.",)- # Write-only: which SignalReportTask row to create when linking a task to a report.- signal_report_task_relationship = serializers.ChoiceField(- choices=[(SIGNAL_REPORT_TASK_RELATIONSHIP_IMPLEMENTATION, "Implementation")],+ # Write-only: recorded as the signals `task_run` artefact type when linking a task to a report.+ signal_report_task_relationship = serializers.CharField(required=False,write_only=True,+ max_length=200,+ help_text=(+ "How the created task relates to the signal report (e.g. 'implementation', 'discussion', "+ "'research'). Recorded as a signals task_run work-log entry; 'implementation' also opens "+ "the auto-start spend gate. Any routing-safe identifier (lowercase letters, numbers, "+ "'_', '-') is accepted."+ ),)json_schema = serializers.JSONField(required=False,@@ -578,6 +589,15 @@ class TaskWriteSerializer(serializers.Serializer):raise serializers.ValidationError("Signal report must belong to the same team")return value+ def validate_signal_report_task_relationship(self, value: str) -> str:+ normalized = value.strip()+ if not _SIGNAL_REPORT_TASK_RELATIONSHIP_RE.fullmatch(normalized):+ raise serializers.ValidationError(+ "Must contain only lowercase letters, numbers, underscores, or hyphens, "+ "and start with a lowercase letter or number."+ )+ return normalized+def validate(self, attrs: dict) -> dict:rel = attrs.get("signal_report_task_relationship")if rel is not None:diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.pyindex 4b65166bba97..11da5408f6a1 100644--- a/products/tasks/backend/tests/test_api.py+++ b/products/tasks/backend/tests/test_api.py@@ -1281,7 +1281,6 @@ class TestTaskAPI(BaseTaskAPITest):"description": "From a signal report","origin_product": "signal_report","signal_report": str(report.id),- # Legacy field old clients still send — accepted and ignored."signal_report_task_relationship": "implementation",},format="json",@@ -1299,6 +1298,58 @@ class TestTaskAPI(BaseTaskAPITest):).exists())+ def test_create_task_with_signal_report_discussion_records_artefact_without_gate_row(self):+ from products.signals.backend.models import SignalReport, SignalReportTask+ from products.signals.backend.task_run_artefacts import (+ TASK_RUN_TYPE_DISCUSSION,+ TASK_RUN_TYPE_IMPLEMENTATION,+ signals_task_ids,+ )++ report = SignalReport.objects.create(team=self.team)+ response = self.client.post(+ "/api/projects/@current/tasks/",+ {+ "title": "Discuss report",+ "description": "Let's discuss this report",+ "origin_product": "signal_report",+ "signal_report": str(report.id),+ "signal_report_task_relationship": "discussion",+ },+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ data = response.json()+ # A discussion link is recorded as a discussion task_run artefact only — it must NOT open the+ # implementation spend gate (no SignalReportTask row, no implementation artefact), otherwise a+ # discuss-the-report task would block the auto-start pipeline.+ self.assertEqual(signals_task_ids(report_id=str(report.id), type=TASK_RUN_TYPE_DISCUSSION), [data["id"]])+ self.assertEqual(signals_task_ids(report_id=str(report.id), type=TASK_RUN_TYPE_IMPLEMENTATION), [])+ self.assertFalse(SignalReportTask.objects.filter(report=report, task_id=data["id"]).exists())++ def test_create_task_with_signal_report_accepts_free_form_relationship(self):+ from products.signals.backend.models import SignalReport, SignalReportTask+ from products.signals.backend.task_run_artefacts import signals_task_ids++ # The relationship is a free-form task_run label — no value is reserved. A non-implementation+ # relationship records only the work-log artefact (no SignalReportTask gate row).+ report = SignalReport.objects.create(team=self.team)+ response = self.client.post(+ "/api/projects/@current/tasks/",+ {+ "title": "Research",+ "description": "From a signal report",+ "origin_product": "signal_report",+ "signal_report": str(report.id),+ "signal_report_task_relationship": "research",+ },+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ data = response.json()+ self.assertEqual(signals_task_ids(report_id=str(report.id), type="research"), [data["id"]])+ self.assertFalse(SignalReportTask.objects.filter(report=report, task_id=data["id"]).exists())+def test_create_task_with_signal_report_different_team_rejected(self):from products.signals.backend.models import SignalReportdiff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.tsindex 92ae4fff64a7..6f6ea91bfa81 100644--- a/products/tasks/frontend/generated/api.schemas.ts+++ b/products/tasks/frontend/generated/api.schemas.ts@@ -600,16 +600,6 @@ export const OriginProductEnumApi = {ImageBuilder: 'image_builder',} as const-/**- * * `implementation` - Implementation- */-export type SignalReportTaskRelationshipEnumApi =- (typeof SignalReportTaskRelationshipEnumApi)[keyof typeof SignalReportTaskRelationshipEnumApi]--export const SignalReportTaskRelationshipEnumApi = {- Implementation: 'implementation',-} as const-/*** * `claude` - claude* * `codex` - codex@@ -695,7 +685,11 @@ export interface TaskWriteApi {* @nullable*/signal_report?: string | null- signal_report_task_relationship?: SignalReportTaskRelationshipEnumApi+ /**+ * How the created task relates to the signal report (e.g. 'implementation', 'discussion', 'research'). Recorded as a signals task_run work-log entry; 'implementation' also opens the auto-start spend gate. Any routing-safe identifier (lowercase letters, numbers, '_', '-') is accepted.+ * @maxLength 200+ */+ signal_report_task_relationship?: string/** JSON schema used to validate the output of the task. */json_schema?: unknown/** If true, this task is for internal use and should not be exposed to end users. */@@ -810,7 +804,11 @@ export interface PatchedTaskWriteApi {* @nullable*/signal_report?: string | null- signal_report_task_relationship?: SignalReportTaskRelationshipEnumApi+ /**+ * How the created task relates to the signal report (e.g. 'implementation', 'discussion', 'research'). Recorded as a signals task_run work-log entry; 'implementation' also opens the auto-start spend gate. Any routing-safe identifier (lowercase letters, numbers, '_', '-') is accepted.+ * @maxLength 200+ */+ signal_report_task_relationship?: string/** JSON schema used to validate the output of the task. */json_schema?: unknown/** If true, this task is for internal use and should not be exposed to end users. */diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.tsindex 13b30c0b8a9a..71ea3c6c5219 100644--- a/products/tasks/frontend/generated/api.zod.ts+++ b/products/tasks/frontend/generated/api.zod.ts@@ -346,6 +346,8 @@ export const tasksCreateBodyTitleMax = 255export const tasksCreateBodyRepositoryMax = 255+export const tasksCreateBodySignalReportTaskRelationshipMax = 200+export const tasksCreateBodyBranchMax = 255export const tasksCreateBodyPendingUserArtifactIdsItemMax = 128@@ -403,9 +405,12 @@ export const TasksCreateBody = /* @__PURE__ */ zod.describe('User-scoped GitHub integration to use for user-authored cloud runs.'),signal_report: zod.uuid().nullish().describe('Signal report this task implements, when created from a report.'),signal_report_task_relationship: zod- .enum(['implementation'])- .describe('\* `implementation` - Implementation')- .optional(),+ .string()+ .max(tasksCreateBodySignalReportTaskRelationshipMax)+ .optional()+ .describe(+ "How the created task relates to the signal report (e.g. 'implementation', 'discussion', 'research'). Recorded as a signals task_run work-log entry; 'implementation' also opens the auto-start spend gate. Any routing-safe identifier (lowercase letters, numbers, '_', '-') is accepted."+ ),json_schema: zod.unknown().optional().describe('JSON schema used to validate the output of the task.'),internal: zod.boolean()@@ -479,6 +484,8 @@ export const tasksUpdateBodyTitleMax = 255export const tasksUpdateBodyRepositoryMax = 255+export const tasksUpdateBodySignalReportTaskRelationshipMax = 200+export const tasksUpdateBodyBranchMax = 255export const tasksUpdateBodyPendingUserArtifactIdsItemMax = 128@@ -536,9 +543,12 @@ export const TasksUpdateBody = /* @__PURE__ */ zod.describe('User-scoped GitHub integration to use for user-authored cloud runs.'),signal_report: zod.uuid().nullish().describe('Signal report this task implements, when created from a report.'),signal_report_task_relationship: zod- .enum(['implementation'])- .describe('\* `implementation` - Implementation')- .optional(),+ .string()+ .max(tasksUpdateBodySignalReportTaskRelationshipMax)+ .optional()+ .describe(+ "How the created task relates to the signal report (e.g. 'implementation', 'discussion', 'research'). Recorded as a signals task_run work-log entry; 'implementation' also opens the auto-start spend gate. Any routing-safe identifier (lowercase letters, numbers, '_', '-') is accepted."+ ),json_schema: zod.unknown().optional().describe('JSON schema used to validate the output of the task.'),internal: zod.boolean()@@ -612,6 +622,8 @@ export const tasksPartialUpdateBodyTitleMax = 255export const tasksPartialUpdateBodyRepositoryMax = 255+export const tasksPartialUpdateBodySignalReportTaskRelationshipMax = 200+export const tasksPartialUpdateBodyBranchMax = 255export const tasksPartialUpdateBodyPendingUserArtifactIdsItemMax = 128@@ -669,9 +681,12 @@ export const TasksPartialUpdateBody = /* @__PURE__ */ zod.describe('User-scoped GitHub integration to use for user-authored cloud runs.'),signal_report: zod.uuid().nullish().describe('Signal report this task implements, when created from a report.'),signal_report_task_relationship: zod- .enum(['implementation'])- .describe('\* `implementation` - Implementation')- .optional(),+ .string()+ .max(tasksPartialUpdateBodySignalReportTaskRelationshipMax)+ .optional()+ .describe(+ "How the created task relates to the signal report (e.g. 'implementation', 'discussion', 'research'). Recorded as a signals task_run work-log entry; 'implementation' also opens the auto-start spend gate. Any routing-safe identifier (lowercase letters, numbers, '_', '-') is accepted."+ ),json_schema: zod.unknown().optional().describe('JSON schema used to validate the output of the task.'),internal: zod.boolean()diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 265d9dc48701..599478fd1c29 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -46723,16 +46723,6 @@ export namespace Schemas {environment?: TaskRunUpdateEnvironmentEnum;}- /**- * * `implementation` - Implementation- */- export type SignalReportTaskRelationshipEnum = typeof SignalReportTaskRelationshipEnum[keyof typeof SignalReportTaskRelationshipEnum];--- export const SignalReportTaskRelationshipEnum = {- Implementation: 'implementation',- } as const;-/*** Request body for creating or updating a task.*@@ -46790,7 +46780,11 @@ export namespace Schemas {* @nullable*/signal_report?: string | null;- signal_report_task_relationship?: SignalReportTaskRelationshipEnum;+ /**+ * How the created task relates to the signal report (e.g. 'implementation', 'discussion', 'research'). Recorded as a signals task_run work-log entry; 'implementation' also opens the auto-start spend gate. Any routing-safe identifier (lowercase letters, numbers, '_', '-') is accepted.+ * @maxLength 200+ */+ signal_report_task_relationship?: string;/** JSON schema used to validate the output of the task. */json_schema?: unknown;/** If true, this task is for internal use and should not be exposed to end users. */@@ -59505,7 +59499,11 @@ export namespace Schemas {* @nullable*/signal_report?: string | null;- signal_report_task_relationship?: SignalReportTaskRelationshipEnum;+ /**+ * How the created task relates to the signal report (e.g. 'implementation', 'discussion', 'research'). Recorded as a signals task_run work-log entry; 'implementation' also opens the auto-start spend gate. Any routing-safe identifier (lowercase letters, numbers, '_', '-') is accepted.+ * @maxLength 200+ */+ signal_report_task_relationship?: string;/** JSON schema used to validate the output of the task. */json_schema?: unknown;/** If true, this task is for internal use and should not be exposed to end users. */