: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
import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { lemonToast } from '@posthog/lemon-ui'
import { pluralize } from 'lib/utils/strings'
import { teamLogic } from 'scenes/teamLogic'
import {
signalsReportsBulkClaim,
signalsReportsReviewersMeCreate,
signalsReportsReviewersMeDestroy,
} from 'products/signals/frontend/generated/api'
import type { ReviewerRemovalReasonEnumApi } from 'products/signals/frontend/generated/api.schemas'
import { signalsReportsBulkClaimBodyIdsMax } from 'products/signals/frontend/generated/api.zod'
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 {
successCount: number
failureCount: number
}
function formatBulkSummary(result: BulkActionResult, verb: 'dismissed' | 'resolved'): string {
const { successCount, failureCount } = result
const pluralized = successCount === 1 ? 'report' : 'reports'
if (failureCount === 0) {
return `${successCount} ${pluralized} ${verb}`
}
return `${successCount} ${pluralized} ${verb}, ${failureCount} failed`
}
function formatUnassignSummary({ successCount, failureCount }: BulkActionResult): string {
if (successCount === 0) {
return `Couldn't unassign you from ${pluralize(failureCount, 'report')}. Try again.`
}
const unassigned = `Unassigned you from ${pluralize(successCount, 'report')}`
return failureCount === 0 ? unassigned : `${unassigned}, ${failureCount} failed`
}
function formatClaimSummary(claimedCount: number, refusedCount: number): string {
const claimed = `Claimed ${pluralize(claimedCount, 'report')}`
const refused =
refusedCount === 1
? '1 report changed before it could be claimed'
: `${refusedCount} reports changed before they could be claimed`
if (refusedCount === 0) {
return claimed
}
return claimedCount === 0 ? refused : `${claimed}. ${refused}`
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface inboxBulkActionsLogicValues {
currentTeamId: number | null // teamLogic
hasSelection: boolean
isClaiming: boolean
isDismissing: boolean
isResolving: boolean
isUnassigning: boolean
selectedCount: number
selectedReportIds: string[]
selectionAnchorId: string | null
visibleReportIds: string[]
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface inboxBulkActionsLogicActions {
bulkClaim: (reportIds: string[]) => {
reportIds: string[]
}
bulkClaimFailure: () => {
value: true
}
bulkClaimSuccess: () => {
value: true
}
bulkDismiss: (dismissal: DismissalFeedback) => {
dismissal: DismissalFeedback
}
bulkDismissFailure: () => {
value: true
}
bulkDismissSuccess: () => {
value: true
}
bulkResolve: (
reason: ResolveReasonValue,
note: string
) => {
note: string
reason: ResolveReasonValue
}
bulkResolveFailure: () => {
value: true
}
bulkResolveSuccess: () => {
value: true
}
bulkUnassignMe: (
reportIds: string[],
reason?: ReviewerRemovalReasonEnumApi
) => {
reason: ReviewerRemovalReasonEnumApi | undefined
reportIds: string[]
}
bulkUnassignMeFailure: () => {
value: true
}
bulkUnassignMeSuccess: () => {
value: true
}
clearSelection: () => {
value: true
}
reportClaimChanged: (
reportId: string,
assignee: SignalReport['assignee']
) => {
assignee: SignalReportAssigneeApi | null | undefined
reportId: string
}
reportReviewersChanged: (
reportId: string,
reviewerUuids: string[]
) => {
reportId: string
reviewerUuids: string[]
}
reportStateChanged: () => {
value: true
}
reportWriteFailed: (reportIds: string[]) => {
reportIds: string[]
}
selectAll: (reportIds: string[]) => {
reportIds: string[]
}
selectRange: (reportId: string) => {
reportId: string
}
setSelectedReportIds: (reportIds: string[]) => {
reportIds: string[]
}
setVisibleReportIds: (reportIds: string[]) => {
reportIds: string[]
}
toggleReportSelection: (reportId: string) => {
reportId: string
}
unassignedMe: (reportIds: string[]) => {
reportIds: string[]
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface inboxBulkActionsLogicMeta {
__keaTypeGenInternalSelectorTypes: {
selectedCount: (selectedReportIds: string[]) => number
hasSelection: (selectedReportIds: string[]) => boolean
}
}
export type inboxBulkActionsLogicType = MakeLogicType<
inboxBulkActionsLogicValues,
inboxBulkActionsLogicActions,
Record<string, any>,
inboxBulkActionsLogicMeta
>
/**
* Multi-select + bulk claim / dismiss / resolve / unassign for the inbox report list. Mirrors desktop
* `inboxReportSelectionStore` (selection state) and `useInboxBulkActions`
* (bulk suppress via `updateSignalReportState`). It owns the selected id set, the rendered row
* order a shift-click ranges over, and the state calls; the card components own the pointer
* gestures that feed it.
*/
export const inboxBulkActionsLogic = kea<inboxBulkActionsLogicType>([
path(['scenes', 'inbox', 'logics', 'inboxBulkActionsLogic']),
connect(() => ({
values: [teamLogic, ['currentTeamId']],
})),
actions({
toggleReportSelection: (reportId: string) => ({ reportId }),
setSelectedReportIds: (reportIds: string[]) => ({ reportIds }),
selectAll: (reportIds: string[]) => ({ reportIds }),
/** Extend the selection from the anchor row to this one, over the rendered order. */
selectRange: (reportId: string) => ({ reportId }),
/** The rows the list currently renders, in order. Also drops selected ids that left the list. */
setVisibleReportIds: (reportIds: string[]) => ({ reportIds }),
clearSelection: true,
/** Suppress every selected report with the chosen reason/note, then clear. */
bulkDismiss: (dismissal: DismissalFeedback) => ({ dismissal }),
bulkDismissSuccess: true,
bulkDismissFailure: true,
/** Resolve every selected report with the chosen reason/note, then clear. */
bulkResolve: (reason: ResolveReasonValue, note: string) => ({ reason, note }),
bulkResolveSuccess: true,
bulkResolveFailure: true,
bulkUnassignMe: (reportIds: string[], reason?: ReviewerRemovalReasonEnumApi) => ({ reportIds, reason }),
bulkUnassignMeSuccess: true,
bulkUnassignMeFailure: true,
/** Claim these reports for the signed-in user in one request, then clear. Agent and task claims are taken
* over; a report a person holds is refused. Every list reloads when the request ends. */
bulkClaim: (reportIds: string[]) => ({ reportIds }),
bulkClaimSuccess: true,
bulkClaimFailure: true,
/** Broadcast that the signed-in user is no longer a suggested reviewer on these reports, so a
* list scoped to them drops the rows in place and every other list stops marking them as theirs. */
unassignedMe: (reportIds: string[]) => ({ reportIds }),
/** Broadcast that a single report changed state elsewhere (dismissed, resolved, or refunded in
* 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 }),
/** Broadcast that a report was claimed or released elsewhere (the detail pane, a row menu), with the
* new assignee (null once released), so every mounted list updates the row's claim in place. */
reportClaimChanged: (reportId: string, assignee: SignalReport['assignee']) => ({ reportId, assignee }),
}),
reducers({
selectedReportIds: [
[] as string[],
{
toggleReportSelection: (state, { reportId }) =>
state.includes(reportId) ? state.filter((id) => id !== reportId) : [...state, reportId],
setSelectedReportIds: (_, { reportIds }) => Array.from(new Set(reportIds)),
selectAll: (_, { reportIds }) => Array.from(new Set(reportIds)),
// Keep the same array when there was nothing to clear, so an Esc with no selection
// costs no re-render.
clearSelection: (state) => (state.length === 0 ? state : []),
// A reload, a filter change, or a report leaving the list must not leave a stale id
// behind: a bulk action on it would fail. Keep the same array when nothing was
// dropped, so an unchanged list does not re-render every card.
setVisibleReportIds: (state, { reportIds }) => {
const visible = new Set(reportIds)
const kept = state.filter((id) => visible.has(id))
return kept.length === state.length ? state : kept
},
},
],
/** The row a shift-click measures its range from: the last row selected without shift. */
selectionAnchorId: [
null as string | null,
{
toggleReportSelection: (_, { reportId }) => reportId,
selectAll: () => null,
clearSelection: () => null,
setVisibleReportIds: (state, { reportIds }) =>
state !== null && !reportIds.includes(state) ? null : state,
},
],
visibleReportIds: [
[] as string[],
{
setVisibleReportIds: (_, { reportIds }) => reportIds,
},
],
isDismissing: [
false,
{
bulkDismiss: () => true,
bulkDismissSuccess: () => false,
bulkDismissFailure: () => false,
},
],
isResolving: [
false,
{
bulkResolve: () => true,
bulkResolveSuccess: () => false,
bulkResolveFailure: () => false,
},
],
isUnassigning: [
false,
{
bulkUnassignMe: () => true,
bulkUnassignMeSuccess: () => false,
bulkUnassignMeFailure: () => false,
},
],
isClaiming: [
false,
{
bulkClaim: () => true,
bulkClaimSuccess: () => false,
bulkClaimFailure: () => false,
},
],
}),
selectors({
selectedCount: [
(s) => [s.selectedReportIds],
(selectedReportIds: string[]): number => selectedReportIds.length,
],
hasSelection: [
(s) => [s.selectedReportIds],
(selectedReportIds: string[]): boolean => selectedReportIds.length > 0,
],
}),
listeners(({ actions, values }) => ({
selectRange: ({ reportId }) => {
const { visibleReportIds, selectionAnchorId, selectedReportIds } = values
const end = visibleReportIds.indexOf(reportId)
if (end === -1) {
return
}
// The anchor only counts while something is selected, because the toggle that removed
// the last selected row still wrote its own id there.
const anchorId = selectedReportIds.length > 0 ? selectionAnchorId : null
// No anchor yet (a shift-click as the first click): treat it as a plain toggle, which
// also sets the anchor for the next shift-click.
const start = anchorId === null ? -1 : visibleReportIds.indexOf(anchorId)
if (start === -1) {
actions.toggleReportSelection(reportId)
return
}
const [from, to] = start <= end ? [start, end] : [end, start]
// The range only covers loaded rows, because `visibleReportIds` is the rendered list.
actions.setSelectedReportIds([...selectedReportIds, ...visibleReportIds.slice(from, to + 1)])
},
bulkDismiss: async ({ dismissal }) => {
const reportIds = values.selectedReportIds
if (reportIds.length === 0) {
actions.bulkDismissFailure()
return
}
// Only the structured reason and repo correction — the free-form note can carry proprietary text.
captureInboxReportAction({
actionType: 'dismiss',
surface: 'bulk_bar',
isBulk: true,
bulkSize: reportIds.length,
extra: {
dismissal_reason: dismissal.reason,
...(dismissal.correctedRepository
? { dismissal_corrected_repository: dismissal.correctedRepository }
: {}),
},
})
const results = await Promise.allSettled(
reportIds.map((id) =>
setReportState(id, {
state: 'suppressed',
...suppressDismissalPayload(dismissal),
})
)
)
const successCount = results.filter((r) => r.status === 'fulfilled').length
const result: BulkActionResult = {
successCount,
failureCount: results.length - successCount,
}
actions.clearSelection()
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.
// A partial failure still surfaces as an error toast ("N dismissed, M failed").
if (result.failureCount > 0) {
lemonToast.error(formatBulkSummary(result, 'dismissed'))
} else {
lemonToast.success(formatBulkSummary(result, 'dismissed'))
}
actions.bulkDismissSuccess()
},
// Same shape as bulkDismiss. A report the backend refuses to resolve from its current status
// (a 409) counts as failed, so the toast says how many were left in place.
bulkResolve: async ({ reason, note }) => {
const reportIds = values.selectedReportIds
if (reportIds.length === 0) {
actions.bulkResolveFailure()
return
}
const trimmedNote = note.trim().slice(0, 4000)
// Only the structured reason — the free-form note can carry proprietary text.
captureInboxReportAction({
actionType: 'resolve',
surface: 'bulk_bar',
isBulk: true,
bulkSize: reportIds.length,
extra: { dismissal_reason: reason },
})
const results = await Promise.allSettled(
reportIds.map((id) =>
setReportState(id, {
state: 'resolved',
dismissal_reason: reason,
...(trimmedNote ? { dismissal_note: trimmedNote } : {}),
})
)
)
const successCount = results.filter((r) => r.status === 'fulfilled').length
const result: BulkActionResult = {
successCount,
failureCount: results.length - successCount,
}
actions.clearSelection()
if (result.successCount === 0) {
lemonToast.error(formatBulkSummary(result, 'resolved'))
actions.bulkResolveFailure()
actions.reportWriteFailed(reportIds)
return
}
if (result.failureCount > 0) {
lemonToast.error(formatBulkSummary(result, 'resolved'))
} else {
lemonToast.success(formatBulkSummary(result, 'resolved'))
}
actions.bulkResolveSuccess()
},
bulkUnassignMe: async ({ reportIds, reason }) => {
if (reportIds.length === 0) {
actions.bulkUnassignMeFailure()
return
}
captureInboxReportAction({
actionType: 'remove_suggested_reviewer',
surface: 'bulk_bar',
isBulk: true,
bulkSize: reportIds.length,
// pinned: analytics property names — renaming breaks dashboards
extra: reason ? { removal_reason: reason } : undefined,
})
const projectId = String(values.currentTeamId)
const results = await Promise.allSettled(
reportIds.map((id) =>
reason
? signalsReportsReviewersMeCreate(projectId, id, { removal_reason: reason })
: signalsReportsReviewersMeDestroy(projectId, id)
)
)
const unassignedIds = reportIds.filter((_, index) => results[index].status === 'fulfilled')
const result: BulkActionResult = {
successCount: unassignedIds.length,
failureCount: reportIds.length - unassignedIds.length,
}
actions.clearSelection()
if (unassignedIds.length > 0) {
actions.unassignedMe(unassignedIds)
}
if (result.failureCount > 0) {
lemonToast.error(formatUnassignSummary(result))
} else {
lemonToast.success(formatUnassignSummary(result))
}
if (result.successCount === 0) {
actions.bulkUnassignMeFailure()
} else {
actions.bulkUnassignMeSuccess()
}
},
bulkClaim: async ({ reportIds }) => {
if (reportIds.length === 0) {
actions.bulkClaimFailure()
return
}
captureInboxReportAction({
actionType: 'claim',
surface: 'bulk_bar',
isBulk: true,
bulkSize: reportIds.length,
})
// The endpoint takes a limited number of ids per call, and a selection across loaded pages can be
// larger, so the ids go in consecutive batches.
let claimedCount = 0
try {
for (let start = 0; start < reportIds.length; start += signalsReportsBulkClaimBodyIdsMax) {
const result = await signalsReportsBulkClaim(String(values.currentTeamId), {
ids: reportIds.slice(start, start + signalsReportsBulkClaimBodyIdsMax),
takeover_agent_claims: true,
})
claimedCount += result.claimed_count
}
} catch {
// The selection stays, so the person can try again once the lists show the server's state.
lemonToast.error(
claimedCount > 0
? `Claimed ${pluralize(claimedCount, 'report')}, but couldn't claim the rest. Try again.`
: `Couldn't claim ${pluralize(reportIds.length, 'report')}. Try again.`
)
actions.bulkClaimFailure()
return
}
actions.clearSelection()
const refusedCount = reportIds.length - claimedCount
const summary = formatClaimSummary(claimedCount, refusedCount)
if (refusedCount > 0) {
lemonToast.error(summary)
} else {
lemonToast.success(summary)
}
if (claimedCount === 0) {
actions.bulkClaimFailure()
} else {
actions.bulkClaimSuccess()
}
},
})),
])