: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): keep claims and edits when an older inbox fetch lands (#125875)
Dylan Martin65e9d2a9e18f
diff --git a/frontend/src/scenes/project-homepage/today/todayLogic.ts b/frontend/src/scenes/project-homepage/today/todayLogic.tsindex f5b7a6074f7d..3eb268806517 100644--- a/frontend/src/scenes/project-homepage/today/todayLogic.ts+++ b/frontend/src/scenes/project-homepage/today/todayLogic.ts@@ -901,6 +901,12 @@ export const todayLogic = kea<todayLogicType>([}}},+ // A verdict that failed without an answer can still have saved, so the list reloads from the server.+ [todayVerdictLogic.actionTypes.setReportVerdictFailure]: () => {+ if (!values.useSampleData) {+ actions.loadTopReports()+ }+ },showMoreForYou: () => {actions.setListExpanded('for_you', true)if (values.canLoadMoreReports) {diff --git a/frontend/src/scenes/project-homepage/today/todayReportLogic.test.ts b/frontend/src/scenes/project-homepage/today/todayReportLogic.test.tsindex 9ffbe9aa60dc..9fddc5200e27 100644--- a/frontend/src/scenes/project-homepage/today/todayReportLogic.test.ts+++ b/frontend/src/scenes/project-homepage/today/todayReportLogic.test.ts@@ -15,6 +15,7 @@ import type { ReportPageApi } from 'products/today/frontend/generated/api.schemaimport { todayReportLogic } from './todayReportLogic'import { todayReportQueueLogic } from './todayReportQueueLogic'+import { todayVerdictLogic } from './todayVerdictLogic'const PAGE: ReportPageApi = {lead: 'Checkout fails for Safari users.',@@ -177,6 +178,29 @@ describe('todayReportLogic', () => {.toNotHaveDispatchedActions([other])})+ // A verdict that timed out can still have saved, so the page must not keep showing the old state.+ test.each([+ { failedReportId: 'report-a', fetches: 2 },+ { failedReportId: 'report-b', fetches: 1 },+ ])('a failed verdict on $failedReportId fetches report-a $fetches times', async ({ failedReportId, fetches }) => {+ const reportGet = jest.fn(() => [200, makeReport({ id: 'report-a' })])+ useMocks({+ get: {+ '/api/projects/:team_id/signals/reports/:id/': reportGet,+ '/api/projects/:team_id/today/reports/:id/page/': () => [200, PAGE],+ },+ })+ initKeaTests()+ const logic = todayReportLogic({ reportId: 'report-a' })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadFullReportSuccess']).toFinishAllListeners()++ todayVerdictLogic.actions.setReportVerdictFailure(failedReportId)+ await expectLogic(logic).toFinishAllListeners()++ expect(reportGet).toHaveBeenCalledTimes(fetches)+ })+test('asks Jev once per mark while a request is in flight and hides the marks when the flag turns off', async () => {const report = makeReport({ actionability: 'immediately_actionable', status: SignalReportStatus.READY })const calls = { keyClauses: 0, figureMarks: 0 }diff --git a/frontend/src/scenes/project-homepage/today/todayReportLogic.ts b/frontend/src/scenes/project-homepage/today/todayReportLogic.tsindex 10bed5a447e3..599d210ade25 100644--- a/frontend/src/scenes/project-homepage/today/todayReportLogic.ts+++ b/frontend/src/scenes/project-homepage/today/todayReportLogic.ts@@ -566,6 +566,12 @@ export const todayReportLogic = kea<todayReportLogicType>([})}return {+ // A verdict that failed without an answer can still have saved, so the page reloads the report.+ [todayVerdictLogic.actionTypes.setReportVerdictFailure]: ({ reportId }: { reportId: string }) => {+ if (reportId === props.reportId) {+ actions.loadFullReport()+ }+ },reportVisited: () => {// A visit with no click on Today is a deep-link: a shared URL, a PostHog AI link, a refresh,// or back / forward.diff --git a/frontend/src/scenes/project-homepage/today/todayVerdictLogic.ts b/frontend/src/scenes/project-homepage/today/todayVerdictLogic.tsindex 5ad054fc6594..a6ccdbacfafe 100644--- a/frontend/src/scenes/project-homepage/today/todayVerdictLogic.ts+++ b/frontend/src/scenes/project-homepage/today/todayVerdictLogic.ts@@ -14,6 +14,7 @@ import { openDismissReportDialog } from 'products/signals/frontend/inbox/componeimport { openResolveReportDialog } from 'products/signals/frontend/inbox/components/shell/ResolveReportDialog'import { captureTodayReportAction } from 'products/signals/frontend/inbox/inboxAnalytics'import { suppressDismissalPayload } from 'products/signals/frontend/inbox/utils/dismissalReasons'+import { withInboxWriteTimeout } from 'products/signals/frontend/inbox/utils/writeTimeout'import type { TodayReportState } from './todayReportState'@@ -201,10 +202,14 @@ export const todayVerdictLogic = kea<todayVerdictLogicType>([setReportVerdict: async ({ target, verdict, surface, feedback, onComplete }) => {const copy = VERDICTS[verdict]try {- await signalsReportsStateCreate(String(values.currentProjectId), target.reportId, {- ...feedback,- state: copy.apiState,- })+ await withInboxWriteTimeout('state', (options) =>+ signalsReportsStateCreate(+ String(values.currentProjectId),+ target.reportId,+ { ...feedback, state: copy.apiState },+ options+ )+ )} catch (error) {actions.setReportVerdictFailure(target.reportId)lemonToast.error((error instanceof ApiError && error.detail) || copy.failure)diff --git a/products/signals/frontend/inbox/components/cards/useReportDismiss.ts b/products/signals/frontend/inbox/components/cards/useReportDismiss.tsindex 1c26abb16db9..a4e1f4971565 100644--- a/products/signals/frontend/inbox/components/cards/useReportDismiss.ts+++ b/products/signals/frontend/inbox/components/cards/useReportDismiss.ts@@ -2,11 +2,11 @@ import { useState } from 'react'import { lemonToast } from '@posthog/lemon-ui'-import api from 'lib/api'-import { captureInboxReportAction, InboxReportActionSurface } from '../../inboxAnalytics'+import { inboxBulkActionsLogic } from '../../logics/inboxBulkActionsLogic'import { SignalReport } from '../../types'import { DismissalFeedback, suppressDismissalPayload } from '../../utils/dismissalReasons'+import { setReportState } from '../../utils/writeTimeout'import { openDismissReportDialog } from '../shell/DismissReportDialog'/**@@ -63,7 +63,7 @@ export function useReportDismiss({// Fallback for standalone usage (e.g. stories) without a bound list logic.setIsDismissing(true)try {- await api.signalReports.setState(reportId, {+ await setReportState(reportId, {state: 'suppressed',...suppressDismissalPayload(dismissal),})@@ -73,6 +73,7 @@ export function useReportDismiss({// shows the user nothing, so a refused dismiss needs this toast. Reject after it// so the reason and note survive for a retry. Matches useReportResolve.lemonToast.error(error?.detail || error?.message || 'Failed to dismiss report')+ inboxBulkActionsLogic.findMounted()?.actions.reportWriteFailed([reportId])throw error} finally {setIsDismissing(false)diff --git a/products/signals/frontend/inbox/components/detail/ReportDetailActions.tsx b/products/signals/frontend/inbox/components/detail/ReportDetailActions.tsxindex edbc890f8ab6..211f3d22eff0 100644--- a/products/signals/frontend/inbox/components/detail/ReportDetailActions.tsx+++ b/products/signals/frontend/inbox/components/detail/ReportDetailActions.tsx@@ -5,7 +5,6 @@ import { type MouseEvent, useState } from 'react'import { IconCheckCircle, IconHide, IconReceipt, IconUndo, IconClock } from '@posthog/icons'import { lemonToast } from '@posthog/lemon-ui'-import api from 'lib/api'import { urls } from 'scenes/urls'import { captureInboxReportAction } from '../../inboxAnalytics'@@ -16,6 +15,7 @@ import { INBOX_REPORT_SECTION_LIST_PARAMS, reportListLogic } from '../../logics/import { SignalReport, SignalReportStatus } from '../../types'import { canMonitorReport, canResolveReport } from '../../utils/reportActions'import { hasMergedReportPullRequest } from '../../utils/reportPullRequests'+import { setReportState } from '../../utils/writeTimeout'import { useReportDismiss } from '../cards/useReportDismiss'import { useReportRefund } from '../cards/useReportRefund'import { useReportResolve } from './useReportResolve'@@ -42,7 +42,7 @@ export function useReportDetailActions(report: SignalReport): ReportDetailActionconst detailLogic = inboxReportDetailLogic({ reportId: report.id, report })const { changeReportState } = useActions(detailLogic)const { reportStateSaving, reportChecks } = useValues(detailLogic)- const { reportStateChanged } = useActions(inboxBulkActionsLogic)+ const { reportStateChanged, reportWriteFailed } = useActions(inboxBulkActionsLogic)const { activeTab } = useValues(inboxSceneLogic)const { loadSelectedReport } = useActions(inboxSceneLogic)const [isRestoring, setIsRestoring] = useState(false)@@ -123,7 +123,7 @@ export function useReportDetailActions(report: SignalReport): ReportDetailAction// the flag-off Archive list, which mounts under the `resolved` key and so isn't found above.setIsRestoring(true)try {- await api.signalReports.setState(report.id, { state: 'potential' })+ await setReportState(report.id, { state: 'potential' })captureInboxReportAction({ report, actionType: 'restore', surface: 'detail_pane' })lemonToast.success('Report restored to inbox')// Broadcast so any mounted list (including that Archive instance) reconciles against the@@ -132,6 +132,7 @@ export function useReportDetailActions(report: SignalReport): ReportDetailActionrouter.actions.push(urls.inbox(activeTab))} catch (error: any) {lemonToast.error(error?.detail || error?.message || 'Failed to restore report')+ reportWriteFailed([report.id])} finally {setIsRestoring(false)}diff --git a/products/signals/frontend/inbox/components/detail/useReportResolve.ts b/products/signals/frontend/inbox/components/detail/useReportResolve.tsindex 085abfb75d16..d05788c3c01c 100644--- a/products/signals/frontend/inbox/components/detail/useReportResolve.ts+++ b/products/signals/frontend/inbox/components/detail/useReportResolve.ts@@ -2,11 +2,11 @@ import { useState } from 'react'import { lemonToast } from '@posthog/lemon-ui'-import api from 'lib/api'-import { captureInboxReportAction, InboxReportActionSurface } from '../../inboxAnalytics'+import { inboxBulkActionsLogic } from '../../logics/inboxBulkActionsLogic'import { SignalReport, SignalReportStatus } from '../../types'import { hasOpenImplementationPr } from '../../utils/reportActions'+import { setReportState } from '../../utils/writeTimeout'import { openResolveReportDialog } from '../shell/ResolveReportDialog'/**@@ -49,7 +49,7 @@ export function useReportResolve({})setIsResolving(true)try {- await api.signalReports.setState(report.id, {+ await setReportState(report.id, {state: 'resolved',dismissal_reason: reason,...(note ? { dismissal_note: note } : {}),@@ -58,6 +58,7 @@ export function useReportResolve({onResolved?.()} catch (error: any) {lemonToast.error(error?.detail || error?.message || 'Failed to resolve report')+ inboxBulkActionsLogic.findMounted()?.actions.reportWriteFailed([report.id])// Reject so LemonDialog keeps the dialog open (the chosen reason and note survive// for a retry) and captures genuine failures. Matches useReportRefund.throw errordiff --git a/products/signals/frontend/inbox/inboxAnalytics.ts b/products/signals/frontend/inbox/inboxAnalytics.tsindex 179f40035c55..c78553b1c04e 100644--- a/products/signals/frontend/inbox/inboxAnalytics.ts+++ b/products/signals/frontend/inbox/inboxAnalytics.ts@@ -36,6 +36,7 @@ export const INBOX_EVENTS = {VALUE_SUMMARY_VIEWED: 'Inbox value summary viewed',VALUE_SUMMARY_DISMISSED: 'Inbox value summary dismissed',PANEL_LOAD_TIMED_OUT: 'Inbox panel load timed out',+ WRITE_TIMED_OUT: 'Inbox write timed out',QUERY_CHANGED: 'Inbox query changed',REPORTS_IMPRESSED: 'Inbox reports impressed',REPORT_OPENED: 'Inbox report opened',@@ -235,6 +236,9 @@ export type InboxPanelName = 'runs' | 'config' | 'sources' | 'scratchpad' | 'fin/** A panel read that carries its own timeout, named so each one's stall rate reads separately. */export type InboxPanelLoad = 'scout_notes' | 'scout_memory'+/** A report write that carries its own timeout. `state` covers dismiss, resolve, restore, and monitoring. */+export type InboxWrite = 'claim' | 'priority' | 'state'+/** Which control moved the report list to a new query. `url` is a shared/deep link being applied. */export type InboxQueryChange =| 'scope'@@ -948,6 +952,14 @@ export function capturePanelLoadTimedOut(params: { load: InboxPanelLoad; timeout})}+/** A report write was aborted for taking too long. Like a stalled panel read, it records no `client_request_failure`. */+export function captureWriteTimedOut(params: { write: InboxWrite; timeoutMs: number }): void {+ captureInboxEvent(INBOX_EVENTS.WRITE_TIMED_OUT, {+ write: params.write,+ timeout_ms: params.timeoutMs,+ })+}+/*** The list moved to a new query — a filter, sort, search, or scope change. `Inbox viewed` fires once* per tab mount, so re-querying an already-open inbox left no trace at all: a user working a filtereddiff --git a/products/signals/frontend/inbox/inboxSceneLogic.test.ts b/products/signals/frontend/inbox/inboxSceneLogic.test.tsindex 42d94958cbcb..7660d1e703c0 100644--- a/products/signals/frontend/inbox/inboxSceneLogic.test.ts+++ b/products/signals/frontend/inbox/inboxSceneLogic.test.ts@@ -1,7 +1,8 @@import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'-import { combineUrl, router } from 'kea-router'/* oxlint-disable react-hooks/rules-of-hooks -- useMocks is a test helper, not a React hook */+import { waitFor } from '@testing-library/react'+import { combineUrl, router } from 'kea-router'import { expectLogic } from 'kea-test-utils'import posthog from 'posthog-js'import type { CaptureOptions } from 'posthog-js'@@ -638,6 +639,62 @@ describe('inboxSceneLogic routing', () => {}})+ // A write that timed out or lost its response can still have saved, so the open report must not keep its+ // local copy. A failure on another report must not refetch this one.+ test.each([+ { failedReportId: 'report-1', fetches: 2 },+ { failedReportId: 'report-2', fetches: 1 },+ ])(+ 'a failed write on $failedReportId fetches the open report $fetches times',+ async ({ failedReportId, fetches }) => {+ const reportGet = mockReportGet()+ mountLogic()+ logic.actions.setSelectedReportId('report-1')+ await expectLogic(logic).toDispatchActions(['loadSelectedReportSuccess'])++ inboxBulkActionsLogic.actions.reportWriteFailed([failedReportId])+ await expectLogic(logic).toFinishAllListeners()++ expect(reportGet).toHaveBeenCalledTimes(fetches)+ }+ )++ it('keeps a claim made while a refresh is in flight, and takes the other fields from the refresh', async () => {+ let releaseRefresh: () => void = () => {}+ const heldRefresh = new Promise<void>((resolve) => {+ releaseRefresh = resolve+ })+ let fetches = 0+ const reportGet = jest.fn(async () => {+ if (fetches++ === 0) {+ return [200, { id: 'report-1', title: 'Crash on login', status: SignalReportStatus.READY }]+ }+ await heldRefresh+ return [+ 200,+ { id: 'report-1', title: 'Crash on login after refresh', status: SignalReportStatus.READY },+ ]+ })+ useMocks({+ get: { '/api/projects/:team_id/signals/reports/report-1/': reportGet },+ post: { '/api/projects/:team_id/signals/reports/:id/viewed/': [204, null] },+ })+ mountLogic()+ logic.actions.setSelectedReportId('report-1')+ await expectLogic(logic).toDispatchActions(['loadSelectedReportSuccess'])++ setTabVisibility('visible')+ await waitFor(() => expect(reportGet).toHaveBeenCalledTimes(2))+ inboxBulkActionsLogic.actions.reportClaimChanged('report-1', myClaim)+ releaseRefresh()+ await expectLogic(logic).toDispatchActions(['loadSelectedReportSuccess'])++ expect(logic.values.selectedReport).toMatchObject({+ title: 'Crash on login after refresh',+ assignee: myClaim,+ })+ })+// The lists behind the detail pane reconcile only on `reportStateChanged`, so a refresh that// lands a new status has to broadcast it. An unconditional broadcast is just as wrong: every// tab return would refresh every mounted section and the refund summary.diff --git a/products/signals/frontend/inbox/inboxSceneLogic.ts b/products/signals/frontend/inbox/inboxSceneLogic.tsindex bb727f9b139a..17eefee53c5c 100644--- a/products/signals/frontend/inbox/inboxSceneLogic.ts+++ b/products/signals/frontend/inbox/inboxSceneLogic.ts@@ -58,6 +58,7 @@ import {} from './types'import { mergeReportRows, selectedFlatListSections } from './utils/flatReportList'import { inboxTabRedirectPath } from './utils/inboxReportUrls'+import { keepFieldsWrittenDuringFetch } from './utils/reportFreshness'import { isReportMetricsEnabled, mergeReportMetricSnapshots, reportNeedsMetricRefresh } from './utils/reportMetrics'import { decodeScoutCreateTemplate } from './utils/scoutTemplateDeepLink'@@ -720,10 +721,11 @@ export const inboxSceneLogic = kea<inboxSceneLogicType>([null as SignalReport | null,{loadSelectedReport: async ({ id }: { id: string }, breakpoint) => {+ const before = values.selectedReportResponsetry {const report = await api.signalReports.get(id)breakpoint()- return report+ return keepFieldsWrittenDuringFetch(report, before, values.selectedReportResponse)} catch (error) {// Discard a superseded load so a slow response for a report the user already// navigated away from can't overwrite the current one (e.g. a stale 404@@ -887,6 +889,12 @@ export const inboxSceneLogic = kea<inboxSceneLogicType>([}),listeners(({ actions, values, cache, selectors }) => ({+ [inboxBulkActionsLogic.actionTypes.reportWriteFailed]: ({ reportIds }: { reportIds: string[] }) => {+ const id = values.selectedReportId+ if (id && reportIds.includes(id)) {+ actions.loadSelectedReport({ id })+ }+ },// A claim from a list row can change the open report. Patch it the way the detail pane's own claim// does, which also skips the copy that pane already patched.[inboxBulkActionsLogic.actionTypes.reportClaimChanged]: ({diff --git a/products/signals/frontend/inbox/logics/inboxBulkActionsLogic.test.ts b/products/signals/frontend/inbox/logics/inboxBulkActionsLogic.test.tsindex 72cf9732b450..549c774537c1 100644--- a/products/signals/frontend/inbox/logics/inboxBulkActionsLogic.test.ts+++ b/products/signals/frontend/inbox/logics/inboxBulkActionsLogic.test.ts@@ -21,6 +21,21 @@ describe('inboxBulkActionsLogic', () => {logic.unmount()})+ // A write that timed out can still have saved, so a bulk action where every write failed must not leave the+ // lists showing the old state.+ it.each([+ {+ action: 'dismiss',+ run: () => logic.actions.bulkDismiss({ reason: 'wontfix_irrelevant', note: '', correctedRepository: null }),+ },+ { action: 'resolve', run: () => logic.actions.bulkResolve('no_action_needed', '') },+ ])('asks every surface to reload after a $action where every write failed', async ({ run }) => {+ useMocks({ post: { '/api/projects/:team_id/signals/reports/:id/state/': () => [500, {}] } })+ logic.actions.setSelectedReportIds(['r1', 'r2'])++ await expectLogic(logic, run).toDispatchActions([logic.actionCreators.reportWriteFailed(['r1', 'r2'])])+ })+it('toggles a report in and out of the selection', async () => {await expectLogic(logic, () => {logic.actions.toggleReportSelection('a')diff --git a/products/signals/frontend/inbox/logics/inboxBulkActionsLogic.ts b/products/signals/frontend/inbox/logics/inboxBulkActionsLogic.tsindex 0a7319d4af6e..09b5c8fcf47b 100644--- a/products/signals/frontend/inbox/logics/inboxBulkActionsLogic.ts+++ b/products/signals/frontend/inbox/logics/inboxBulkActionsLogic.ts@@ -2,7 +2,6 @@ import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectimport { lemonToast } from '@posthog/lemon-ui'-import api from 'lib/api'import { pluralize } from 'lib/utils/strings'import { teamLogic } from 'scenes/teamLogic'@@ -18,6 +17,7 @@ import type { SignalReportAssigneeApi } from '../../generated/api.schemas'import { captureInboxReportAction } from '../inboxAnalytics'import type { SignalReport } from '../types'import { type DismissalFeedback, type ResolveReasonValue, suppressDismissalPayload } from '../utils/dismissalReasons'+import { setReportState } from '../utils/writeTimeout'/** Tally of a bulk operation that ran one request per selected report. */interface BulkActionResult {@@ -134,6 +134,9 @@ export interface inboxBulkActionsLogicActions {reportStateChanged: () => {value: true}+ reportWriteFailed: (reportIds: string[]) => {+ reportIds: string[]+ }selectAll: (reportIds: string[]) => {reportIds: string[]}@@ -215,6 +218,9 @@ export const inboxBulkActionsLogic = kea<inboxBulkActionsLogicType>([* the detail pane), so every mounted list reconciles itself. Persisting the change is the* caller's responsibility. */reportStateChanged: true,+ /** Broadcast that a write to these reports failed. A write that timed out or lost its response can still+ * have saved, so every mounted list and the open report reload from the server. */+ reportWriteFailed: (reportIds: string[]) => ({ reportIds }),/** Broadcast that a report's suggested reviewers were saved, with the PostHog user uuids now on* it, so a list scoped to a reviewer who is no longer on the report drops the row in place. */reportReviewersChanged: (reportId: string, reviewerUuids: string[]) => ({ reportId, reviewerUuids }),@@ -348,7 +354,7 @@ export const inboxBulkActionsLogic = kea<inboxBulkActionsLogicType>([})const results = await Promise.allSettled(reportIds.map((id) =>- api.signalReports.setState(id, {+ setReportState(id, {state: 'suppressed',...suppressDismissalPayload(dismissal),})@@ -362,10 +368,10 @@ export const inboxBulkActionsLogic = kea<inboxBulkActionsLogicType>([actions.clearSelection()- // Total failure: nothing was suppressed, so there's nothing for the list to drop.if (result.successCount === 0) {lemonToast.error(formatBulkSummary(result, 'dismissed'))actions.bulkDismissFailure()+ actions.reportWriteFailed(reportIds)return}// Any success (partial or full) must reload so the suppressed reports leave the list.@@ -396,7 +402,7 @@ export const inboxBulkActionsLogic = kea<inboxBulkActionsLogicType>([})const results = await Promise.allSettled(reportIds.map((id) =>- api.signalReports.setState(id, {+ setReportState(id, {state: 'resolved',dismissal_reason: reason,...(trimmedNote ? { dismissal_note: trimmedNote } : {}),@@ -414,6 +420,7 @@ export const inboxBulkActionsLogic = kea<inboxBulkActionsLogicType>([if (result.successCount === 0) {lemonToast.error(formatBulkSummary(result, 'resolved'))actions.bulkResolveFailure()+ actions.reportWriteFailed(reportIds)return}if (result.failureCount > 0) {diff --git a/products/signals/frontend/inbox/logics/inboxReportDetailLogic.test.ts b/products/signals/frontend/inbox/logics/inboxReportDetailLogic.test.tsindex 682759cd1829..090d8c8d2f14 100644--- a/products/signals/frontend/inbox/logics/inboxReportDetailLogic.test.ts+++ b/products/signals/frontend/inbox/logics/inboxReportDetailLogic.test.ts@@ -256,6 +256,39 @@ describe('inboxReportDetailLogic', () => {})+ // A write that fails without an answer, such as one that timed out, can still have saved on the server.+ it.each<{ write: string; mocks: Parameters<typeof useMocks>[0]; run: () => void }>([+ {+ write: 'claim',+ mocks: { post: { '/api/projects/:team_id/signals/reports/:id/claim/': () => [500, {}] } },+ run: () => logic.actions.setReportClaimed(true),+ },+ {+ write: 'priority',+ mocks: { put: { '/api/projects/:team_id/signals/reports/:id/priority/': () => [500, {}] } },+ run: () => logic.actions.updatePriority('P2'),+ },+ {+ write: 'state',+ mocks: { post: { '/api/projects/:team_id/signals/reports/:id/state/': () => [500, {}] } },+ run: () => logic.actions.changeReportState('potential'),+ },+ ])('asks every surface to reload the report after a failed $write write', async ({ mocks, run }) => {+ const bulkLogic = inboxBulkActionsLogic()+ bulkLogic.mount()+ const errorToast = jest.spyOn(lemonToast, 'error')+ try {+ useMocks(mocks)+ await expectLogic(bulkLogic, run).toDispatchActions([+ bulkLogic.actionCreators.reportWriteFailed([REPORT.id]),+ ])+ expect(errorToast).toHaveBeenCalledTimes(1)+ } finally {+ errorToast.mockRestore()+ bulkLogic.unmount()+ }+ })+it('keeps the saved priority after a failure and allows retrying', async () => {useMocks({ put: { '/api/projects/:team_id/signals/reports/:id/priority/': () => [500, {}] } })logic.actions.updatePriority('P2')diff --git a/products/signals/frontend/inbox/logics/inboxReportDetailLogic.ts b/products/signals/frontend/inbox/logics/inboxReportDetailLogic.tsindex 008a9440137d..47cf297f78ae 100644--- a/products/signals/frontend/inbox/logics/inboxReportDetailLogic.ts+++ b/products/signals/frontend/inbox/logics/inboxReportDetailLogic.ts@@ -90,6 +90,7 @@ import { EnrichedReviewer, ReviewerRemoval, SignalReport, SignalReportArtefact,import { ChartPlacements, resolveChartPlacements } from '../utils/chartPlacement'import { isReportClaimable, reportClaimant, requestReportClaim } from '../utils/reportClaim'import { reportPullRequests, primaryReportPullRequest, type ReportPullRequest } from '../utils/reportPullRequests'+import { withInboxWriteTimeout } from '../utils/writeTimeout'import { inboxBulkActionsLogic } from './inboxBulkActionsLogic'/** Run statuses that count as terminal. Mirrors desktop `isTerminalStatus` / `ReportTasksSection`. */@@ -1704,7 +1705,14 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([}actions.setReportStateSaving(true)try {- await signalsReportsStateCreate(String(ApiConfig.getCurrentProjectId()), props.reportId, { state })+ await withInboxWriteTimeout('state', (options) =>+ signalsReportsStateCreate(+ String(ApiConfig.getCurrentProjectId()),+ props.reportId,+ { state },+ options+ )+ )inboxBulkActionsLogic.findMounted()?.actions.reportStateChanged()const scene = inboxSceneLogic.findMounted()if (scene?.values.selectedReportId === props.reportId) {@@ -1712,6 +1720,7 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([}} catch {lemonToast.error("Couldn't update this report. Refresh it and try again.")+ inboxBulkActionsLogic.findMounted()?.actions.reportWriteFailed([props.reportId])} finally {actions.setReportStateSaving(false)}@@ -1725,8 +1734,11 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([actions.setPrioritySaving(true)let updated: SignalReportApitry {- updated = await signalsReportsPriorityUpdate(String(teamId), props.reportId, { priority })+ updated = await withInboxWriteTimeout('priority', (options) =>+ signalsReportsPriorityUpdate(String(teamId), props.reportId, { priority }, options)+ )} catch {+ inboxBulkActionsLogic.findMounted()?.actions.reportWriteFailed([props.reportId])if (inboxReportDetailLogic.isMounted(props)) {actions.setPrioritySaving(false)lemonToast.error("Couldn't save the priority. Try again.")@@ -1772,11 +1784,8 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([if (inboxReportDetailLogic.isMounted(props)) {actions.setClaimSaving(false)lemonToast.error(outcome.message)- if (outcome.conflict) {- // Reload so the page shows who holds the claim now.- scene?.actions.loadSelectedReport({ id: props.reportId })- }}+ inboxBulkActionsLogic.findMounted()?.actions.reportWriteFailed([props.reportId])return}const updated = outcome.updateddiff --git a/products/signals/frontend/inbox/logics/reportListLogic.test.ts b/products/signals/frontend/inbox/logics/reportListLogic.test.tsindex 605b9f842a6f..bd79a2a19296 100644--- a/products/signals/frontend/inbox/logics/reportListLogic.test.ts+++ b/products/signals/frontend/inbox/logics/reportListLogic.test.ts@@ -244,6 +244,29 @@ describe('reportListLogic', () => {expect(logic.values.reports).toHaveLength(FIRST_PAGE.length + SECOND_PAGE.length)})+ it('keeps a claim made while the first page reloads, which the reload read before the claim saved', async () => {+ let releasePage: () => void = () => {}+ const heldPage = new Promise<void>((resolve) => {+ releasePage = resolve+ })+ useMocks({+ get: {+ [REPORTS_URL]: async () => {+ await heldPage+ return [200, { count: FIRST_PAGE.length, next: null, previous: null, results: FIRST_PAGE }]+ },+ },+ })++ logic.actions.loadReports()+ logic.actions.setReportAssignee(FIRST_PAGE[0].id, myClaim)+ releasePage()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.reports.find((r) => r.id === FIRST_PAGE[0].id)?.assignee).toEqual(myClaim)+ expect(logic.values.reports.find((r) => r.id === FIRST_PAGE[1].id)?.assignee).toBeUndefined()+ })+it('keeps a row removed while the next page is in flight out of the appended list', async () => {let releasePage: () => void = () => {}const heldPage = new Promise<void>((resolve) => {diff --git a/products/signals/frontend/inbox/logics/reportListLogic.ts b/products/signals/frontend/inbox/logics/reportListLogic.tsindex cf0e8c8b1b5f..0926c2007f35 100644--- a/products/signals/frontend/inbox/logics/reportListLogic.ts+++ b/products/signals/frontend/inbox/logics/reportListLogic.ts@@ -39,8 +39,10 @@ import {import type { SignalReportPriority } from '../types'import { DismissalFeedback, ResolveReasonValue, suppressDismissalPayload } from '../utils/dismissalReasons'import { requestReportClaim } from '../utils/reportClaim'+import { keepRowFieldsWrittenDuringFetch } from '../utils/reportFreshness'import { isReportMetricsEnabled, mergeReportMetricSnapshots, reportNeedsMetricRefresh } from '../utils/reportMetrics'import { reportPullRequests, primaryReportPullRequest } from '../utils/reportPullRequests'+import { setReportState } from '../utils/writeTimeout'import { inboxBulkActionsLogic } from './inboxBulkActionsLogic'import { buildSignalReportListSortParams, inboxFiltersLogic } from './inboxFiltersLogic'import type { InboxCreatedWindow, InboxFilterState, InboxSortDirection, InboxSortField } from './inboxFiltersLogic'@@ -162,6 +164,19 @@ export function shouldDefaultToEntireProject(input: {)}+/**+ * A write that timed out or lost its response can still have saved, so every surface that shows the report reloads+ * it. This list can be mounted without the inbox scene, for example in a row menu, and then only reloads itself.+ */+function reloadAfterFailedWrite(reportId: string, refresh: () => void): void {+ const bulkActions = inboxBulkActionsLogic.findMounted()+ if (bulkActions) {+ bulkActions.actions.reportWriteFailed([reportId])+ } else {+ refresh()+ }+}+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface reportListLogicValues {featureFlags: FeatureFlagsSet // featureFlagLogic@@ -554,6 +569,7 @@ export const reportListLogic = kea<reportListLogicType>([const params = values.listApiParamsconst requestContext = requestContextFromValues(values)cache.firstPageRequestId = (cache.firstPageRequestId ?? 0) + 1+ const rowsBefore = values.reportsResponse?.results// nosemgrep: prefer-codegen-api-namespaced-signals -- the Inbox renders the handwritten SignalReport. The generated report type is wider (string status and priority, read-only arrays), so the list calls move to generated types together with the Inbox.const response = await api.signalReports.list({...listRequestParams(params),@@ -562,7 +578,16 @@ export const reportListLogic = kea<reportListLogicType>([})// A newer first-page request for a changed query supersedes this one.breakpoint()- return { ...response, requestParams: params, requestContext }+ return {+ ...response,+ results: keepRowFieldsWrittenDuringFetch(+ response.results,+ rowsBefore,+ values.reportsResponse?.results+ ),+ requestParams: params,+ requestContext,+ }},loadMoreReports: async (): Promise<ReportListResponse> => {const params = values.listApiParams@@ -948,7 +973,7 @@ export const reportListLogic = kea<reportListLogicType>([dismissReport: async ({ reportId, dismissal }) => {actions.removeReport(reportId)try {- await api.signalReports.setState(reportId, {+ await setReportState(reportId, {state: 'suppressed',...suppressDismissalPayload(dismissal),})@@ -957,7 +982,7 @@ export const reportListLogic = kea<reportListLogicType>([inboxBulkActionsLogic.actions.reportStateChanged()} catch (error: any) {lemonToast.error(error?.detail || error?.message || 'Failed to dismiss report')- actions.refresh()+ reloadAfterFailedWrite(reportId, actions.refresh)}},// Mark a report done without an inbox PR (transition to `resolved`). Optimistically drops it@@ -965,7 +990,7 @@ export const reportListLogic = kea<reportListLogicType>([resolveReport: async ({ reportId, reason, note }) => {actions.removeReport(reportId)try {- await api.signalReports.setState(reportId, {+ await setReportState(reportId, {state: 'resolved',dismissal_reason: reason,...(note ? { dismissal_note: note } : {}),@@ -975,7 +1000,7 @@ export const reportListLogic = kea<reportListLogicType>([inboxBulkActionsLogic.actions.reportStateChanged()} catch (error: any) {lemonToast.error(error?.detail || error?.message || 'Failed to resolve report')- actions.refresh()+ reloadAfterFailedWrite(reportId, actions.refresh)}},// Restore a suppressed report back to the inbox (transition to `potential`). Optimistically@@ -984,7 +1009,7 @@ export const reportListLogic = kea<reportListLogicType>([const report = values.reports.find((r) => r.id === reportId)actions.removeReport(reportId)try {- await api.signalReports.setState(reportId, { state: 'potential' })+ await setReportState(reportId, { state: 'potential' })// Fire only after the restore persists, matching ReportDetailActions' fallback path.captureInboxReportAction({ report, actionType: 'restore', surface })lemonToast.success('Report restored to inbox')@@ -996,7 +1021,7 @@ export const reportListLogic = kea<reportListLogicType>([inboxBulkActionsLogic.actions.reportStateChanged()} catch (error: any) {lemonToast.error(error?.detail || error?.message || 'Failed to restore report')- actions.refresh()+ reloadAfterFailedWrite(reportId, actions.refresh)}},// A bulk dismiss or resolve happens in the singleton; refresh this section once it lands so@@ -1010,6 +1035,7 @@ export const reportListLogic = kea<reportListLogicType>([// this section against the server so the report leaves its section and joins Resolved or// Dismissed, counts included.[inboxBulkActionsLogic.actionTypes.reportStateChanged]: () => actions.refresh(),+ [inboxBulkActionsLogic.actionTypes.reportWriteFailed]: () => actions.refresh(),// A reviewer edit can take a report out of this list's reviewer scope. Drop the row in place// rather than refetch: a refetch reloads only the first page, which loses the scroll position.[inboxBulkActionsLogic.actionTypes.reportReviewersChanged]: ({ reportId, reviewerUuids }) => {@@ -1081,7 +1107,7 @@ export const reportListLogic = kea<reportListLogicType>([lemonToast.error(outcome.message)// Reload so the row shows who holds the claim now. A request that failed without an answer// may still have saved the claim.- actions.refresh()+ reloadAfterFailedWrite(report.id, actions.refresh)return}// Every mounted list updates the row, and the Claimed by you list gains or drops it.diff --git a/products/signals/frontend/inbox/utils/reportClaim.ts b/products/signals/frontend/inbox/utils/reportClaim.tsindex ada5466f891a..4084aa0c5cea 100644--- a/products/signals/frontend/inbox/utils/reportClaim.ts+++ b/products/signals/frontend/inbox/utils/reportClaim.ts@@ -4,6 +4,7 @@ import { signalsReportsClaim, signalsReportsRetrieve } from 'products/signals/frimport type { SignalReportApi, SignalReportClaimApi, _UserApi } from 'products/signals/frontend/generated/api.schemas'import { SignalReport, SignalReportStatus } from '../types'+import { withInboxWriteTimeout } from './writeTimeout'/** Statuses the claim endpoint accepts. Mirrors the server's `CLAIMABLE_REPORT_STATUSES`. */const CLAIMABLE_STATUSES: ReadonlySet<SignalReportStatus> = new Set([@@ -43,7 +44,7 @@ type FreshClaimAttempt = { fresh: SignalReportApi | null; updated: SignalReportAasync function claimFromFreshReport(teamId: string, reportId: string): Promise<FreshClaimAttempt> {let fresh: SignalReportApitry {- fresh = await signalsReportsRetrieve(teamId, reportId)+ fresh = await withInboxWriteTimeout('claim', (options) => signalsReportsRetrieve(teamId, reportId, options))} catch {return { fresh: null, updated: null }}@@ -51,7 +52,13 @@ async function claimFromFreshReport(teamId: string, reportId: string): Promise<Freturn { fresh, updated: null }}try {- return { fresh, updated: await signalsReportsClaim(teamId, reportId, reportClaimRequest(fresh, true)) }+ const request = reportClaimRequest(fresh, true)+ return {+ fresh,+ updated: await withInboxWriteTimeout('claim', (options) =>+ signalsReportsClaim(teamId, reportId, request, options)+ ),+ }} catch {return { fresh, updated: null }}@@ -72,7 +79,13 @@ export async function requestReportClaim(claimed: boolean): Promise<ReportClaimOutcome> {try {- return { ok: true, updated: await signalsReportsClaim(teamId, report.id, reportClaimRequest(report, claimed)) }+ const request = reportClaimRequest(report, claimed)+ return {+ ok: true,+ updated: await withInboxWriteTimeout('claim', (options) =>+ signalsReportsClaim(teamId, report.id, request, options)+ ),+ }} catch (error) {const conflict = error instanceof ApiError && error.status === 409const retry = conflict && claimed ? await claimFromFreshReport(teamId, report.id) : nulldiff --git a/products/signals/frontend/inbox/utils/reportFreshness.ts b/products/signals/frontend/inbox/utils/reportFreshness.tsnew file mode 100644index 000000000000..e2bdfa2b036a--- /dev/null+++ b/products/signals/frontend/inbox/utils/reportFreshness.ts@@ -0,0 +1,52 @@+import { objectsEqual } from 'lib/utils/objects'++import { SignalReport } from '../types'++type ReportCopy = Pick<SignalReport, 'id' | 'assignee' | 'priority'>+type WrittenFields = Partial<Pick<SignalReport, 'assignee' | 'priority'>>++function fieldsWrittenBetween(before: ReportCopy, current: ReportCopy): WrittenFields {+ const written: WrittenFields = {}+ if (!objectsEqual(current.assignee ?? null, before.assignee ?? null)) {+ written.assignee = current.assignee+ }+ if (current.priority !== before.priority) {+ written.priority = current.priority+ }+ return written+}++/**+ * A claim or a priority edit patches the local copy of a report while a fetch for it is in flight. The fetch can+ * have read the report before that write saved, and a claim does not change `updated_at`, so the response can't be+ * ordered by timestamp. Compare the copy from before the fetch with the copy now, and keep each field that the page+ * wrote in between.+ */+export function keepFieldsWrittenDuringFetch<T extends ReportCopy>(+ fetched: T,+ before: ReportCopy | null | undefined,+ current: ReportCopy | null | undefined+): T {+ if (!before || !current || current === before) {+ return fetched+ }+ if (before.id !== fetched.id || current.id !== fetched.id) {+ return fetched+ }+ const written = fieldsWrittenBetween(before, current)+ return Object.keys(written).length > 0 ? { ...fetched, ...written } : fetched+}++/** {@link keepFieldsWrittenDuringFetch} for each row of a fetched list. */+export function keepRowFieldsWrittenDuringFetch<T extends ReportCopy>(+ fetched: T[],+ before: ReportCopy[] | null | undefined,+ current: ReportCopy[] | null | undefined+): T[] {+ if (!before || !current || before === current) {+ return fetched+ }+ const beforeById = new Map(before.map((row) => [row.id, row]))+ const currentById = new Map(current.map((row) => [row.id, row]))+ return fetched.map((row) => keepFieldsWrittenDuringFetch(row, beforeById.get(row.id), currentById.get(row.id)))+}diff --git a/products/signals/frontend/inbox/utils/writeTimeout.test.ts b/products/signals/frontend/inbox/utils/writeTimeout.test.tsnew file mode 100644index 000000000000..4a3459f0ef14--- /dev/null+++ b/products/signals/frontend/inbox/utils/writeTimeout.test.ts@@ -0,0 +1,37 @@+import posthog from 'posthog-js'++import { PromiseTimeoutError } from 'lib/utils/async'++import { INBOX_CLIENT, INBOX_EVENTS } from '../inboxAnalytics'+import { INBOX_WRITE_TIMEOUT_MS, withInboxWriteTimeout } from './writeTimeout'++jest.mock('posthog-js')++describe('withInboxWriteTimeout', () => {+ beforeEach(() => {+ jest.useFakeTimers()+ ;(posthog.capture as jest.Mock).mockClear()+ })++ afterEach(() => {+ jest.useRealTimers()+ })++ it('fails a write that never settles, aborts it, and records which write stalled', async () => {+ let signal: AbortSignal | undefined+ const outcome = withInboxWriteTimeout('claim', (options) => {+ signal = options.signal+ return new Promise<void>(() => {})+ }).catch((error) => error)++ jest.advanceTimersByTime(INBOX_WRITE_TIMEOUT_MS)++ expect(await outcome).toBeInstanceOf(PromiseTimeoutError)+ expect(signal?.aborted).toBe(true)+ expect(+ (posthog.capture as jest.Mock).mock.calls+ .filter(([event]) => event === INBOX_EVENTS.WRITE_TIMED_OUT)+ .map(([, properties]) => properties)+ ).toEqual([{ inbox_client: INBOX_CLIENT, write: 'claim', timeout_ms: INBOX_WRITE_TIMEOUT_MS }])+ })+})diff --git a/products/signals/frontend/inbox/utils/writeTimeout.ts b/products/signals/frontend/inbox/utils/writeTimeout.tsnew file mode 100644index 000000000000..5f60cd45417a--- /dev/null+++ b/products/signals/frontend/inbox/utils/writeTimeout.ts@@ -0,0 +1,40 @@+import { ApiConfig } from 'lib/api'+import { PromiseTimeoutError, withTimeout } from 'lib/utils/async'++import { signalsReportsStateCreate } from 'products/signals/frontend/generated/api'+import type { SignalReportApi } from 'products/signals/frontend/generated/api.schemas'++import { captureWriteTimedOut } from '../inboxAnalytics'+import type { InboxWrite } from '../inboxAnalytics'+import type { SignalReport, SignalReportStateRequest } from '../types'++/**+ * How long a report write may stay in flight. A control stays disabled until its write settles, so a write that+ * never settles leaves the control disabled with no way out. Well above a healthy write, so a slow but live one+ * still lands.+ */+export const INBOX_WRITE_TIMEOUT_MS = 30_000++/**+ * Bound a report write, so one that never settles fails and reaches the caller's error path. The server can still+ * apply a write that timed out, so callers reload after a failure instead of trusting their local copy.+ */+export async function withInboxWriteTimeout<T>(+ write: InboxWrite,+ request: (options: { signal: AbortSignal }) => Promise<T>+): Promise<T> {+ try {+ return await withTimeout((signal) => request({ signal }), INBOX_WRITE_TIMEOUT_MS, `${write} write timed out`)+ } catch (error) {+ if (error instanceof PromiseTimeoutError) {+ captureWriteTimedOut({ write, timeoutMs: INBOX_WRITE_TIMEOUT_MS })+ }+ throw error+ }+}++export function setReportState(reportId: SignalReport['id'], data: SignalReportStateRequest): Promise<SignalReportApi> {+ return withInboxWriteTimeout('state', (options) =>+ signalsReportsStateCreate(String(ApiConfig.getCurrentProjectId()), reportId, data, options)+ )+}