: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
fix(signals): disable create pr while a pr task is running (#84645)
Georgiy Tarasovbdd8b1d00844
diff --git a/products/signals/frontend/inbox/components/detail/ReportDetailActions.tsx b/products/signals/frontend/inbox/components/detail/ReportDetailActions.tsxindex b22ba7c78245..38945c912476 100644--- a/products/signals/frontend/inbox/components/detail/ReportDetailActions.tsx+++ b/products/signals/frontend/inbox/components/detail/ReportDetailActions.tsx@@ -12,6 +12,7 @@ import { captureInboxReportAction } from '../../inboxAnalytics'import { inboxSceneLogic } from '../../inboxSceneLogic'import { inboxTaskKickoffLogic } from '../../inboxTaskKickoffLogic'import { inboxBulkActionsLogic } from '../../logics/inboxBulkActionsLogic'+import { inboxReportDetailLogic } from '../../logics/inboxReportDetailLogic'import { INBOX_FLAT_TAB_LIST_PARAMS, reportListLogic } from '../../logics/reportListLogic'import { ACTIONABLE_ACTIONABILITY_VALUES, SignalReport, SignalReportStatus } from '../../types'import { useReportArchive } from '../cards/useReportArchive'@@ -62,6 +63,9 @@ function canCreateImplementationPr(report: SignalReport): boolean {*/export function useReportDetailActions(report: SignalReport): ReportDetailAction[] {const { isCreatingPr, aiConsentDisabledReason } = useValues(inboxTaskKickoffLogic)+ // Already mounted by `ReportDetail` with these same props, so this reads the loaded value+ // rather than starting a second fetch.+ const { hasLiveImplementationTask } = useValues(inboxReportDetailLogic({ reportId: report.id, report }))const { createPrFromReport } = useActions(inboxTaskKickoffLogic)const { reportArchived } = useActions(inboxBulkActionsLogic)const { activeTab } = useValues(inboxSceneLogic)@@ -191,7 +195,11 @@ export function useReportDetailActions(report: SignalReport): ReportDetailActionicon: <IconPullRequest />,loading: isCreatingPr,tooltip: 'Have Self-driving open a pull request for this report',- disabledReason: aiConsentDisabledReason ?? undefined,+ disabledReason:+ aiConsentDisabledReason ??+ (hasLiveImplementationTask+ ? 'A PR task already exists for this report. Open it in the task log to continue.'+ : undefined),onClick: () => {captureInboxReportAction({ report, actionType: 'create_pr', surface: 'detail_pane' })createPrFromReport(report)diff --git a/products/signals/frontend/inbox/logics/inboxReportDetailLogic.test.ts b/products/signals/frontend/inbox/logics/inboxReportDetailLogic.test.tsindex 0ea15499f61f..f9188badf609 100644--- a/products/signals/frontend/inbox/logics/inboxReportDetailLogic.test.ts+++ b/products/signals/frontend/inbox/logics/inboxReportDetailLogic.test.ts@@ -4,12 +4,47 @@ import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'+import { TaskRunStatus } from 'products/posthog_ai/frontend/types/taskTypes'++import { ReportTaskPurpose } from '../components/detail/artefactTypes'import { SignalReport } from '../types'-import { inboxReportDetailLogic } from './inboxReportDetailLogic'+import { ReportTaskEntry, hasLiveImplementationTask, inboxReportDetailLogic } from './inboxReportDetailLogic'const REPORT = { id: 'report-1', status: 'ready', title: 'Checkout errors spiked' } as unknown as SignalReport+const linkedTask = (purpose: ReportTaskPurpose, status: TaskRunStatus | null): ReportTaskEntry =>+ ({+ task: { latest_run: status ? { status } : null },+ purpose,+ purposeLabel: purpose,+ startedAt: '2026-01-01T00:00:00Z',+ }) as unknown as ReportTaskEntry+describe('inboxReportDetailLogic', () => {+ describe('hasLiveImplementationTask', () => {+ // Only `failed` and `cancelled` hand the report's implementation slot back server-side, so a+ // completed or still-running task has to keep the action disabled. Reusing the logic's+ // TERMINAL_RUN_STATUSES (which includes `completed`) is the tempting mistake these rows catch:+ // it would offer a second PR the server answers with a 429.+ it.each([+ { label: 'a task with no run yet', status: null, holdsSlot: true },+ { label: 'a not-started run', status: TaskRunStatus.NOT_STARTED, holdsSlot: true },+ { label: 'a queued run', status: TaskRunStatus.QUEUED, holdsSlot: true },+ { label: 'a run in progress', status: TaskRunStatus.IN_PROGRESS, holdsSlot: true },+ { label: 'a completed run', status: TaskRunStatus.COMPLETED, holdsSlot: true },+ { label: 'a failed run', status: TaskRunStatus.FAILED, holdsSlot: false },+ { label: 'a cancelled run', status: TaskRunStatus.CANCELLED, holdsSlot: false },+ ])('$label holds the report implementation slot: $holdsSlot', ({ status, holdsSlot }) => {+ expect(hasLiveImplementationTask([linkedTask('implementation', status)])).toBe(holdsSlot)+ })++ it('ignores tasks that are not implementations, and an unloaded list', () => {+ expect(hasLiveImplementationTask([linkedTask('research', TaskRunStatus.IN_PROGRESS)])).toBe(false)+ expect(hasLiveImplementationTask([linkedTask('other', TaskRunStatus.IN_PROGRESS)])).toBe(false)+ expect(hasLiveImplementationTask(null)).toBe(false)+ })+ })+describe('feedback note submission', () => {let logic: ReturnType<typeof inboxReportDetailLogic.build>let notePosts: number@@ -125,4 +160,76 @@ describe('inboxReportDetailLogic', () => {expect(logic.values.prChecksError).toBeTruthy()})})++ describe('report task polling', () => {+ let logic: ReturnType<typeof inboxReportDetailLogic.build>+ let artefactRequests: number++ beforeEach(() => {+ artefactRequests = 0+ useMocks({+ get: {+ '/api/projects/:team_id/signals/reports/:id/artefacts/': () => {+ artefactRequests += 1+ return { results: [] }+ },+ '/api/projects/:team_id/signals/reports/:id/signals/': [],+ '/api/projects/:team_id/signals/reports/available_reviewers/': [],+ },+ })+ initKeaTests()+ logic = inboxReportDetailLogic({ reportId: REPORT.id, report: REPORT })+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ })++ // `ready` is not one of the active statuses, so the report's own status never starts the poll.+ // An implementation run under it still settles, and a failed or cancelled one hands the Create PR+ // slot back, so the run has to hold the poll open by itself or the action stays disabled until the+ // pane is reopened. A completed run must not hold it open: it keeps the slot for good, and polling+ // past it would never observe a change.+ it.each([+ { label: 'no linked tasks', tasks: [], polls: false },+ { label: 'an implementation with no run yet', tasks: [linkedTask('implementation', null)], polls: true },+ {+ label: 'an implementation in progress',+ tasks: [linkedTask('implementation', TaskRunStatus.IN_PROGRESS)],+ polls: true,+ },+ {+ label: 'a completed implementation',+ tasks: [linkedTask('implementation', TaskRunStatus.COMPLETED)],+ polls: false,+ },+ {+ label: 'a failed implementation',+ tasks: [linkedTask('implementation', TaskRunStatus.FAILED)],+ polls: false,+ },+ {+ label: 'a research task in progress',+ tasks: [linkedTask('research', TaskRunStatus.IN_PROGRESS)],+ polls: false,+ },+ ])('a ready report with $label polls: $polls', ({ tasks, polls }) => {+ logic.actions.loadReportTasksSuccess(tasks)++ expect(logic.values.shouldPollReportTasks).toBe(polls)+ })++ it('refreshes the artefact log once a PR task starts', async () => {+ await expectLogic(logic).toFinishAllListeners()+ const beforeKickoff = artefactRequests++ // Without this the gate keeps reading the pre-kickoff task list, so a ready report offers+ // Create PR a second time and the server answers the press with a 429.+ logic.actions.createPrSuccess()+ await expectLogic(logic).toFinishAllListeners()++ expect(artefactRequests).toBe(beforeKickoff + 1)+ })+ })})diff --git a/products/signals/frontend/inbox/logics/inboxReportDetailLogic.ts b/products/signals/frontend/inbox/logics/inboxReportDetailLogic.tsindex 9d368425b3e7..11f087df4276 100644--- a/products/signals/frontend/inbox/logics/inboxReportDetailLogic.ts+++ b/products/signals/frontend/inbox/logics/inboxReportDetailLogic.ts@@ -61,6 +61,7 @@ import {captureInboxReportFeedbackNote,InboxReportFeedbackSentiment,} from '../inboxAnalytics'+import { inboxTaskKickoffLogic } from '../inboxTaskKickoffLogic'import {EnrichedReviewer,SignalReport,@@ -73,6 +74,12 @@ import { ChartPlacements, resolveChartPlacements } from '../utils/chartPlacement/** Run statuses that count as terminal. Mirrors desktop `isTerminalStatus` / `ReportTasksSection`. */const TERMINAL_RUN_STATUSES: TaskRunStatus[] = [TaskRunStatus.COMPLETED, TaskRunStatus.FAILED, TaskRunStatus.CANCELLED]+// A report funds one implementation task at a time, enforced server-side by+// `_live_implementation_exists` in products/signals/backend/task_run_artefacts.py. Only a failed or+// cancelled run hands the slot back there, so `completed` is deliberately absent: reusing+// TERMINAL_RUN_STATUSES here would offer a second PR the server then refuses.+const IMPLEMENTATION_SLOT_RELEASING_STATUSES: TaskRunStatus[] = [TaskRunStatus.FAILED, TaskRunStatus.CANCELLED]+// The task↔report association is the `task_run` artefact log now (the legacy `/tasks/` endpoint is// gone), and the activity timeline renders the whole log. Pull a generous page so early entries// (the first task runs, repo selection) stay visible on reports with many findings — matching the@@ -93,6 +100,38 @@ export interface ReportTaskEntry {startedAt: string}+/**+ * Whether an implementation task still holds this report's single implementation slot, which makes a+ * manual "Create PR" fail with a `signal_report_task_cap` 429.+ *+ * Approximates the server predicate with what the client has: only `latest_run` rather than every+ * run, and a shipped PR is read off the report instead (`hasImplementationPr`). Unloaded tasks read+ * as no live implementation, so a cold load leaves the action enabled and the 429 stays the backstop+ * rather than blocking a legitimate first press.+ */+export function hasLiveImplementationTask(reportTasks: ReportTaskEntry[] | null): boolean {+ return (reportTasks ?? []).some(+ (entry) =>+ entry.purpose === 'implementation' &&+ !IMPLEMENTATION_SLOT_RELEASING_STATUSES.includes(entry.task.latest_run?.status ?? TaskRunStatus.NOT_STARTED)+ )+}++/**+ * Whether an implementation run is still moving, which is what the Create PR gate waits on.+ *+ * Unlike `hasLiveImplementationTask` this counts `completed` as settled, because a completed run+ * holds the report's slot for good and no later change can hand it back. Reusing the slot predicate+ * here would leave the poll running forever on a finished implementation.+ */+export function implementationRunInFlight(reportTasks: ReportTaskEntry[] | null): boolean {+ return (reportTasks ?? []).some(+ (entry) =>+ entry.purpose === 'implementation' &&+ !TERMINAL_RUN_STATUSES.includes(entry.task.latest_run?.status ?? TaskRunStatus.NOT_STARTED)+ )+}+// While the report is still being worked, poll linked tasks every 5s. Mirrors desktop.const ACTIVE_STATUSES: SignalReportStatus[] = [SignalReportStatus.CANDIDATE,@@ -210,6 +249,7 @@ export interface inboxReportDetailLogicValues {feedbackNoteSubmitting: booleanfeedbackSentiment: InboxReportFeedbackSentiment | nullhasImplementationPr: boolean+ hasLiveImplementationTask: booleanhasPersonalGithub: booleaninlineThreadCount: numberinlineThreadsByFile: Record<string, ReviewThread[]>@@ -244,11 +284,15 @@ export interface inboxReportDetailLogicValues {reportTasksLoading: booleanselectedTask: ReportTaskEntry | nullselectedTaskId: string | null+ shouldPollReportTasks: booleantrailingCharts: ReportChartApi[]}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface inboxReportDetailLogicActions {+ createPrSuccess: () => {+ value: true+ } // inboxTaskKickoffLogiccloseDraftThread: () => {value: true}@@ -467,6 +511,7 @@ export interface inboxReportDetailLogicMeta {isUpdatingReviewers: (optimisticReviewers: EnrichedReviewer[] | null) => booleanreportReviewers: (reportArtefacts: SignalReportArtefact[] | null) => EnrichedReviewer[] | nullisReportActive: (report: SignalReport | null) => boolean+ shouldPollReportTasks: (isReportActive: boolean, reportTasks: ReportTaskEntry[] | null) => booleanhasImplementationPr: (report: SignalReport | null) => booleanprChecksBackedOff: (prChecksConsecutiveFailures: number) => booleanhasPersonalGithub: (personalIntegrations: PersonalGitHubIntegration[]) => boolean@@ -492,6 +537,7 @@ export interface inboxReportDetailLogicMeta {user: null | import('~/types').UserType) => AvailableReviewerOption[]isReResearch: (reportTasks: ReportTaskEntry[] | null) => boolean+ hasLiveImplementationTask: (reportTasks: ReportTaskEntry[] | null) => booleanprimaryTask: (reportTasks: ReportTaskEntry[] | null) => ReportTaskEntry | nullselectedTask: (reportTasks: ReportTaskEntry[] | null,@@ -521,6 +567,8 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([connect(() => ({// Personal GitHub connection state gates the inline comment composer (comments post as the user).values: [personalIntegrationsLogic, ['integrations as personalIntegrations']],+ // Starting a PR task writes to the artefact log, which is where the Create PR gate reads from.+ actions: [inboxTaskKickoffLogic, ['createPrSuccess']],})),actions({@@ -882,6 +930,16 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([(s) => [s.report],(report: SignalReport | null): boolean => (report ? ACTIVE_STATUSES.includes(report.status) : false),],+ // Poll the artefact log while something can still change it. A report being worked is the usual+ // case, but a `ready` report can hold an implementation run too, and that run settling is what+ // hands the Create PR slot back. Without this clause the action stays disabled on a ready report+ // until the pane is reopened, and the server's 429 cannot correct it because the failure runs the+ // other way: the press is refused in the UI that the server would now accept.+ shouldPollReportTasks: [+ (s) => [s.isReportActive, s.reportTasks],+ (isReportActive: boolean, reportTasks: ReportTaskEntry[] | null): boolean =>+ isReportActive || implementationRunInFlight(reportTasks),+ ],// Whether the report has a shipped implementation PR — gates the PR checks/comments fetch + poll.hasImplementationPr: [(s) => [s.report],@@ -1072,6 +1130,10 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([return hasInFlight && hasPriorTerminal},],+ hasLiveImplementationTask: [+ (s) => [s.reportTasks],+ (reportTasks: ReportTaskEntry[] | null): boolean => hasLiveImplementationTask(reportTasks),+ ],// The default task whose run log is shown: prefer one still in motion, tie-break by most-recent// link. Mirrors desktop `AgentRunDetail`'s `pickPrimaryTask`.primaryTask: [@@ -1105,7 +1167,7 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([],}),- listeners(({ actions, values, cache, props }) => ({+ listeners(({ actions, values, props }) => ({rateReport: ({ sentiment }) => {if (!values.report) {return@@ -1350,19 +1412,13 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([actions.loadReportDiff({ artefactId: commit.id })}},- // Poll the artefact log only while the report is active; stop once it reaches a terminal status- // (or is unloaded). Tasks are re-derived via `loadReportArtefactsSuccess`. Mirrors desktop- // `useReportTasks` gating. The keyed disposable replaces any running interval on re-add and is- // torn down automatically on unmount / tab hide.+ // A PR task started from this pane is not in the artefact log the gate was computed from, so+ // refresh it. This is also what starts the task poll for a ready report, whose status alone+ // never gets one going.+ createPrSuccess: () => {+ actions.loadReportArtefacts()+ },setReport: () => {- if (values.isReportActive) {- cache.disposables.add(() => {- const interval = setInterval(() => actions.loadReportArtefacts(), REPORT_TASKS_POLL_INTERVAL_MS)- return () => clearInterval(interval)- }, 'reportTasksPoll')- } else {- cache.disposables.dispose('reportTasksPoll')- }// Load the PR checks/comments once the report has a shipped PR. The recurring checks poll// is registered once in `afterMount` (not here) so it isn't torn down and restarted every// time the shell hands us a fresh `report` prop — which would starve the 15s cadence.@@ -1393,6 +1449,19 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([actions.loadAvailableReviewers()// Seed the report from props so polling is gated on its status from the first tick.actions.setReport(props.report ?? null)+ // Register the artefact-log poll once for the lifetime of the mount and let each tick decide+ // whether to fetch. Re-arming it from `setReport` instead would reset the 5s cadence on every+ // report prop the shell hands down, which is the starvation the PR-checks poll below avoids.+ // Auto-disposed on unmount / hidden tab.+ cache.disposables.add(() => {+ const interval = setInterval(() => {+ if (!values.shouldPollReportTasks) {+ return+ }+ actions.loadReportArtefacts()+ }, REPORT_TASKS_POLL_INTERVAL_MS)+ return () => clearInterval(interval)+ }, 'reportTasksPoll')// Register the PR-checks poll once for the lifetime of the mount — the tick re-checks whether// the report has a PR (and whether GitHub keeps failing), so it stays correct as the report// prop churns without the interval ever being torn down and restarted (which would keep