: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(signals): add a bulk claim endpoint and claim action to the inbox (#125225)
Dylan Martinfe661882c274
diff --git a/products/signals/backend/report_assignments.py b/products/signals/backend/report_assignments.pyindex f21b777153cc..7455c7f6c1d3 100644--- a/products/signals/backend/report_assignments.py+++ b/products/signals/backend/report_assignments.py@@ -103,7 +103,9 @@ class PullRequestDetails:merged_at: datetime | None = None-def assignment_snapshot(report: SignalReport, assignment: ReportClaim | None) -> AssignmentSnapshot:+def assignment_snapshot(+ report: SignalReport, assignment: ReportClaim | None, *, include_pull_request: bool = True+) -> AssignmentSnapshot:assignee: AssigneeSnapshot | None = Noneif assignment is not None:assignee = AssigneeSnapshot(@@ -116,7 +118,11 @@ def assignment_snapshot(report: SignalReport, assignment: ReportClaim | None) ->from products.signals.backend.implementation_pr import fetch_implementation_pr_state_for_reportsimplementation_pr: PullRequestSnapshot | None = None- pr = fetch_implementation_pr_state_for_reports([str(report.id)], team_id=report.team_id).get(str(report.id))+ pr = (+ fetch_implementation_pr_state_for_reports([str(report.id)], team_id=report.team_id).get(str(report.id))+ if include_pull_request+ else None+ )if pr is not None:parsed = GitHubIntegration.parse_pull_request_url(pr.url)implementation_pr = {@@ -415,7 +421,11 @@ def claim_report(locked_report = SignalReport.objects.select_for_update(no_key=True).get(id=report.id, team_id=report.team_id)import_report_pull_requests(locked_report, notify_reviewers=True)assignment = get_active_claim(team_id=report.team_id, report_id=report.id)- before = assignment_snapshot(locked_report, assignment)+ # Only the pull requests in this call change the implementation PR, so a claim without any skips reading+ # it, which a bulk claim would otherwise do twice per report. A task actor's claim also links the task's+ # runs to the report, so it keeps the full read.+ include_pull_request = bool(details) or actor.task_id is not None+ before = assignment_snapshot(locked_report, assignment, include_pull_request=include_pull_request)if claim_id and (assignment is None or str(assignment.claim_id) != claim_id):raise ReportClaimConflict("This claim is no longer active.")if claim_id and assignment is not None and not actor_works_under_claim(assignment, actor):@@ -466,7 +476,7 @@ def claim_report(if details:apply_report_completion(locked_report)- after = assignment_snapshot(locked_report, assignment)+ after = assignment_snapshot(locked_report, assignment, include_pull_request=include_pull_request)if before == after:return assignmentdiff --git a/products/signals/backend/test/test_signal_report_assignment_api.py b/products/signals/backend/test/test_signal_report_assignment_api.pyindex c3f7069902fa..17f7909a86aa 100644--- a/products/signals/backend/test/test_signal_report_assignment_api.py+++ b/products/signals/backend/test/test_signal_report_assignment_api.py@@ -5,7 +5,9 @@ from posthog.test.base import APIBaseTestfrom unittest.mock import MagicMock, call, patchfrom django.apps import apps+from django.db import connectionfrom django.test import SimpleTestCase+from django.test.utils import CaptureQueriesContextfrom django.utils import timezonefrom parameterized import parameterized@@ -987,6 +989,97 @@ class TestSignalReportAssignmentAPI(APIBaseTest):assert len(users) == len(reports)assert {user.id for user in users.values()} == {self.user.id}+ def _bulk_claim_url(self) -> str:+ return f"/api/projects/{self.team.id}/signals/reports/bulk_claim/"++ def test_bulk_claim_reports_each_id_without_reaching_other_teams(self):+ ready = self._create_report()+ dismissed = self._create_report(report_status=SignalReport.Status.SUPPRESSED)+ other_team = Team.objects.create(organization=self.organization, name="Other team")+ foreign = self._create_report(team=other_team)+ unknown = "00000000-0000-0000-0000-000000000000"++ response = self.client.post(+ self._bulk_claim_url(),+ data={"ids": [str(ready.id), str(dismissed.id), str(foreign.id), unknown, str(ready.id)]},+ format="json",+ )++ assert response.status_code == status.HTTP_200_OK, response.json()+ body = response.json()+ assert [(row["id"], row["outcome"]) for row in body["results"]] == [+ (str(ready.id), "claimed"),+ (str(dismissed.id), "conflict"),+ (str(foreign.id), "not_found"),+ (unknown, "not_found"),+ ]+ assert (body["claimed_count"], body["conflict_count"], body["not_found_count"]) == (1, 1, 2)+ claim = get_active_claim(team_id=self.team.id, report_id=ready.id)+ assert claim is not None and claim.actor_user_id == self.user.id+ assert get_active_claim(team_id=other_team.id, report_id=foreign.id) is None++ @parameterized.expand(+ [+ ("an agent, without takeover", "agent", False, "conflict", SignalActorKind.AGENT),+ ("an agent, with takeover", "agent", True, "claimed", SignalActorKind.USER),+ ("a person, with takeover", "person", True, "conflict", SignalActorKind.USER),+ ]+ )+ def test_bulk_claim_takes_over_only_agent_claims_on_request(+ self, _name: str, holder: str, takeover: bool, outcome: str, kind_after: str+ ) -> None:+ report = self._create_report()+ teammate = User.objects.create_and_join(self.organization, "[email protected]", None)+ if holder == "agent":+ self.client.post(self._claim_url(report), data={}, format="json", headers=self._agent_headers("codex"))+ else:+ self.client.force_login(teammate)+ self.client.post(self._claim_url(report), data={}, format="json")+ self.client.force_login(self.user)++ response = self.client.post(+ self._bulk_claim_url(), data={"ids": [str(report.id)], "takeover_agent_claims": takeover}, format="json"+ )++ assert response.status_code == status.HTTP_200_OK, response.json()+ assert response.json()["results"][0]["outcome"] == outcome+ claim = get_active_claim(team_id=self.team.id, report_id=report.id)+ assert claim is not None and claim.actor_kind == kind_after+ assert claim.actor_user_id == (teammate.id if holder == "person" else self.user.id)++ def test_claim_with_a_pull_request_logs_the_implementation_pr_change(self):+ report = self._create_report()+ pr_url = "https://github.com/example/app/pull/7"++ response = self.client.post(self._claim_url(report), data={"pr_url": pr_url}, format="json")++ assert response.status_code == status.HTTP_200_OK, response.json()+ log = ActivityLog.objects.get(+ team_id=self.team.id, scope="SignalReport", item_id=str(report.id), activity="assignment_changed"+ )+ assert log.detail is not None+ pr_change = next(change for change in log.detail["changes"] if change["field"] == "implementation_pr")+ assert pr_change["before"] is None+ assert pr_change["after"]["url"] == pr_url++ def test_bulk_claim_adds_a_fixed_number_of_queries_per_report(self):+ def queries_for(count: int) -> int:+ ids = [str(self._create_report(title=f"Report {i}").id) for i in range(count)]+ with CaptureQueriesContext(connection) as ctx:+ response = self.client.post(self._bulk_claim_url(), data={"ids": ids}, format="json")+ assert response.status_code == status.HTTP_200_OK+ assert response.json()["claimed_count"] == count+ return len(ctx.captured_queries)++ # The first call fills caches the later ones reuse, so it is not measured.+ queries_for(1)+ for_two, for_three, for_four = (queries_for(n) for n in (2, 3, 4))++ per_report = for_three - for_two+ assert for_four - for_three == per_report+ assert per_report <= 11+ assert for_two - 2 * per_report <= 15+def test_claimed_report_remains_in_default_actionable_list(self):report = self._create_report()self.client.post(self._claim_url(report), data={}, format="json")diff --git a/products/signals/backend/views.py b/products/signals/backend/views.pyindex e17024b96371..68f19f55aab6 100644--- a/products/signals/backend/views.py+++ b/products/signals/backend/views.py@@ -143,6 +143,7 @@ from products.signals.backend.models import (ArtefactAttribution,AutonomyPriority,InvalidStatusTransition,+ SignalActorKind,SignalReport,SignalReportAction,SignalReportArtefact,@@ -777,6 +778,15 @@ _CORRECTED_REPOSITORY_MAX_LENGTH = 140_CORRECTED_REPOSITORY_RE = re.compile(r"^[^/\s]+/[^/\s]+$")+class SignalReportBulkClaimOutcome(models.TextChoices):+ """Per-id result of a bulk claim. Mirrors the single-report claim responses:+ `claimed` ~ 200, `conflict` ~ 409, `not_found` ~ 404."""++ CLAIMED = "claimed", "claimed"+ CONFLICT = "conflict", "conflict"+ NOT_FOUND = "not_found", "not_found"++class SignalReportBulkStateOutcome(models.TextChoices):"""Per-id result of a bulk state transition. Mirrors the single-report responses:`transitioned` ~ 200, `skipped` ~ 409 (transition not allowed), `failed` ~ 400."""@@ -946,6 +956,56 @@ class SignalReportBulkStateResponseSerializer(serializers.Serializer):not_found_count = serializers.IntegerField(help_text="Number of requested ids not visible to the caller.")+class SignalReportBulkClaimRequestSerializer(serializers.Serializer):+ ids = serializers.ListField(+ child=serializers.UUIDField(),+ allow_empty=False,+ min_length=1,+ max_length=SIGNAL_REPORT_BULK_STATE_MAX_IDS,+ help_text=(+ "Report ids to claim for the caller in one call (1–"+ f"{SIGNAL_REPORT_BULK_STATE_MAX_IDS}). Duplicates are de-duplicated. Each id is claimed "+ "independently, so a report that cannot be claimed does not block the rest."+ ),+ )+ takeover_agent_claims = serializers.BooleanField(+ default=False,+ help_text=(+ "Take over a report that an agent or an internal task holds. A report that a person holds "+ "directly is never taken over and comes back as a conflict."+ ),+ )+++class SignalReportBulkClaimResultSerializer(serializers.Serializer):+ id = serializers.UUIDField(help_text="The report id this result refers to.")+ # A CharField like the bulk-state outcome, so the response enum cannot collide with another+ # product's `OutcomeEnum` in the shared OpenAPI schema. Values come from SignalReportBulkClaimOutcome.+ outcome = serializers.CharField(+ help_text=(+ "One of: claimed, conflict, not_found. claimed: the caller holds the claim, including when it "+ "already did. conflict: the claim was refused, because someone else holds the report or its "+ "status does not allow a claim (a 409 on the single-report endpoint). not_found: no report "+ "with this id is visible to you."+ ),+ )+ detail = serializers.CharField(+ required=False,+ allow_null=True,+ help_text="Human-readable explanation for a conflict or not_found outcome.",+ )+++class SignalReportBulkClaimResponseSerializer(serializers.Serializer):+ results = SignalReportBulkClaimResultSerializer(+ many=True,+ help_text="One result per requested id, in request order (after de-duplication).",+ )+ claimed_count = serializers.IntegerField(help_text="Number of reports the caller now holds.")+ conflict_count = serializers.IntegerField(help_text="Number of reports whose claim was refused.")+ not_found_count = serializers.IntegerField(help_text="Number of requested ids not visible to the caller.")++class SignalReportMergeRequestSerializer(serializers.Serializer):source_report_ids = serializers.ListField(child=serializers.UUIDField(),@@ -1753,9 +1813,9 @@ class SignalReportViewSet(if self.action in {"list", "section_counts"}:qs = self._apply_signal_report_ranking_filters(qs)qs = self._prefetch_signal_report_priority_artefacts(qs)- if self.action not in {"bulk_state", "section_counts"}:- # `bulk_state` answers with one outcome per id, never a serialized report, and the list- # ordering that reads this value does not apply to it either.+ if self.action not in {"bulk_state", "bulk_claim", "section_counts"}:+ # `bulk_state` and `bulk_claim` answer with one outcome per id, never a serialized report, and+ # the list ordering that reads this value does not apply to them either.qs = self._annotate_is_suggested_reviewer(qs)qs = self._prefetch_signal_report_ranking_score(qs)if self.action not in self._MULTI_REPORT_ACTIONS:@@ -1819,7 +1879,7 @@ class SignalReportViewSet(}# Actions that work on many reports at once, so per-row annotations are wasted work there.- _MULTI_REPORT_ACTIONS = frozenset({"list", "bulk_state", "section_counts"})+ _MULTI_REPORT_ACTIONS = frozenset({"list", "bulk_state", "bulk_claim", "section_counts"})# Actions allowed to resolve a suppressed report by ID even without an explicit# `status` filter. These are the read/reopen paths the inbox's Dismissed tab needs:@@ -1838,6 +1898,7 @@ class SignalReportViewSet({"state","bulk_state",+ "bulk_claim","retrieve","signals","refund",@@ -4317,6 +4378,72 @@ class SignalReportViewSet(})+ @validated_request(+ request_serializer=SignalReportBulkClaimRequestSerializer,+ responses={200: OpenApiResponse(response=SignalReportBulkClaimResponseSerializer)},+ summary="Claim many signal reports",+ description=(+ "Claim many reports for the current user, internal task, or external agent in one call. Each id is "+ "claimed independently, and the call is 200 even when some claims are refused: inspect `results` "+ "and the counts. Use the single-report claim endpoint to release a claim or to add pull requests."+ ),+ operation_id="signals_reports_bulk_claim",+ )+ @action(detail=False, methods=["post"], url_path="bulk_claim", required_scopes=["task:write"])+ def bulk_claim(self, request: ValidatedRequest, *args: object, **kwargs: object) -> Response:+ data = request.validated_data+ ordered_ids = list(dict.fromkeys(str(raw_id) for raw_id in data["ids"]))+ reports_by_id = {str(report.id): report for report in self.get_queryset().filter(id__in=ordered_ids)}+ actor = self._request_attribution()+ claims = get_active_claims(team_id=self.team.id, report_ids=list(reports_by_id))+ user = cast(User, request.user)+ was_impersonated = is_impersonated_session(request)++ results: list[dict] = []+ counts: dict[str, int] = {outcome.value: 0 for outcome in SignalReportBulkClaimOutcome}+ for report_id in ordered_ids:+ report = reports_by_id.get(report_id)+ detail: str | None = None+ if report is None:+ outcome = SignalReportBulkClaimOutcome.NOT_FOUND+ detail = "No report with this id is visible to you."+ else:+ claim = claims.get(report_id)+ # The expected claim id makes the server refuse the takeover when a person claims the+ # report between the read above and this write.+ takeover_claim_id = (+ str(claim.claim_id)+ if data["takeover_agent_claims"]+ and claim is not None+ and claim.actor_kind in (SignalActorKind.AGENT, SignalActorKind.TASK)+ and not actor_works_under_claim(claim, actor)+ else None+ )+ try:+ claim_report(+ report=report,+ actor=actor,+ user=user,+ was_impersonated=was_impersonated,+ takeover=takeover_claim_id is not None,+ takeover_claim_id=takeover_claim_id,+ )+ outcome = SignalReportBulkClaimOutcome.CLAIMED+ except ReportClaimConflict as err:+ outcome = SignalReportBulkClaimOutcome.CONFLICT+ detail = str(err)+ results.append({"id": report_id, "outcome": outcome.value, "detail": detail})+ counts[outcome.value] += 1++ return Response(+ {+ "results": results,+ "claimed_count": counts[SignalReportBulkClaimOutcome.CLAIMED.value],+ "conflict_count": counts[SignalReportBulkClaimOutcome.CONFLICT.value],+ "not_found_count": counts[SignalReportBulkClaimOutcome.NOT_FOUND.value],+ }+ )+def _signals_pr_refunds_enabled(self) -> bool:# Server-side feature gate, keyed on the org (the refund window is the org's billing# period). Same call shape as the quota-limiting data-retention flag check.diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex 7be17c2801c4..a1686ff95876 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -5905,6 +5905,40 @@ export interface SignalReportBulkStateResponseApi {not_found_count: number}+export interface SignalReportBulkClaimRequestApi {+ /**+ * Report ids to claim for the caller in one call (1–100). Duplicates are de-duplicated. Each id is claimed independently, so a report that cannot be claimed does not block the rest.+ * @minItems 1+ * @maxItems 100+ */+ ids: string[]+ /** Take over a report that an agent or an internal task holds. A report that a person holds directly is never taken over and comes back as a conflict. */+ takeover_agent_claims?: boolean+}++export interface SignalReportBulkClaimResultApi {+ /** The report id this result refers to. */+ id: string+ /** One of: claimed, conflict, not_found. claimed: the caller holds the claim, including when it already did. conflict: the claim was refused, because someone else holds the report or its status does not allow a claim (a 409 on the single-report endpoint). not_found: no report with this id is visible to you. */+ outcome: string+ /**+ * Human-readable explanation for a conflict or not_found outcome.+ * @nullable+ */+ detail?: string | null+}++export interface SignalReportBulkClaimResponseApi {+ /** One result per requested id, in request order (after de-duplication). */+ results: SignalReportBulkClaimResultApi[]+ /** Number of reports the caller now holds. */+ claimed_count: number+ /** Number of reports whose claim was refused. */+ conflict_count: number+ /** Number of requested ids not visible to the caller. */+ not_found_count: number+}+/*** * `passing` - Passing* * `failing` - Failingdiff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.tsindex 12063db4bf23..1db2d903b973 100644--- a/products/signals/frontend/generated/api.ts+++ b/products/signals/frontend/generated/api.ts@@ -99,6 +99,8 @@ import type {SignalReportArtefactLogCreateApi,SignalReportArtefactWriteApi,SignalReportArtefactWriteResponseApi,+ SignalReportBulkClaimRequestApi,+ SignalReportBulkClaimResponseApi,SignalReportBulkStateRequestApi,SignalReportBulkStateResponseApi,SignalReportCheckApi,@@ -1519,6 +1521,27 @@ export const signalsReportsBulkStateCreate = async (})}+export const getSignalsReportsBulkClaimUrl = (projectId: string) => {+ return `/api/projects/${projectId}/signals/reports/bulk_claim/`+}++/**+ * Claim many reports for the current user, internal task, or external agent in one call. Each id is claimed independently, and the call is 200 even when some claims are refused: inspect `results` and the counts. Use the single-report claim endpoint to release a claim or to add pull requests.+ * @summary Claim many signal reports+ */+export const signalsReportsBulkClaim = async (+ projectId: string,+ signalReportBulkClaimRequestApi: SignalReportBulkClaimRequestApi,+ options?: RequestInit+): Promise<SignalReportBulkClaimResponseApi> => {+ return apiMutator<SignalReportBulkClaimResponseApi>(getSignalsReportsBulkClaimUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(signalReportBulkClaimRequestApi),+ })+}+export const getSignalsReportsPrCiStatusesUrl = (projectId: string, params: SignalsReportsPrCiStatusesParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.tsindex a3ce8dcb2586..117a8ec9c308 100644--- a/products/signals/frontend/generated/api.zod.ts+++ b/products/signals/frontend/generated/api.zod.ts@@ -1421,6 +1421,30 @@ export const SignalsReportsBulkStateCreateBody = /* @__PURE__ */ zod.object({),})+/**+ * Claim many reports for the current user, internal task, or external agent in one call. Each id is claimed independently, and the call is 200 even when some claims are refused: inspect `results` and the counts. Use the single-report claim endpoint to release a claim or to add pull requests.+ * @summary Claim many signal reports+ */+export const signalsReportsBulkClaimBodyIdsMax = 100++export const signalsReportsBulkClaimBodyTakeoverAgentClaimsDefault = false++export const SignalsReportsBulkClaimBody = /* @__PURE__ */ zod.object({+ ids: zod+ .array(zod.uuid())+ .min(1)+ .max(signalsReportsBulkClaimBodyIdsMax)+ .describe(+ 'Report ids to claim for the caller in one call (1–100). Duplicates are de-duplicated. Each id is claimed independently, so a report that cannot be claimed does not block the rest.'+ ),+ takeover_agent_claims: zod+ .boolean()+ .default(signalsReportsBulkClaimBodyTakeoverAgentClaimsDefault)+ .describe(+ 'Take over a report that an agent or an internal task holds. A report that a person holds directly is never taken over and comes back as a conflict.'+ ),+})+export const signalsReportsReadStateCreateBodyReportIdsMax = 100export const SignalsReportsReadStateCreateBody = /* @__PURE__ */ zod.object({diff --git a/products/signals/frontend/inbox/components/cards/ReportCard.test.tsx b/products/signals/frontend/inbox/components/cards/ReportCard.test.tsxindex e7e3b013b2cb..04b7eede4565 100644--- a/products/signals/frontend/inbox/components/cards/ReportCard.test.tsx+++ b/products/signals/frontend/inbox/components/cards/ReportCard.test.tsx@@ -287,6 +287,11 @@ describe('ReportCard', () => {hold: () => jest.spyOn(api, 'delete').mockReturnValue(new Promise<never>(() => {})),start: () => logic.actions.bulkUnassignMe(['r-1']),},+ {+ action: 'claim',+ hold: () => jest.spyOn(api, 'create').mockReturnValue(new Promise<never>(() => {})),+ start: () => logic.actions.bulkClaim(['r-1']),+ },])('locks the selection while a bulk $action is running', ({ hold, start }) => {const pending = hold()act(() => {diff --git a/products/signals/frontend/inbox/components/cards/useReportCardSelection.ts b/products/signals/frontend/inbox/components/cards/useReportCardSelection.tsindex 9f18f3e44bb9..94906e54265d 100644--- a/products/signals/frontend/inbox/components/cards/useReportCardSelection.ts+++ b/products/signals/frontend/inbox/components/cards/useReportCardSelection.ts@@ -40,7 +40,7 @@ export interface ReportCardSelection {* pointer events into its actions, and it does nothing at all on a row the list marks unselectable.*/export function useReportCardSelection(reportId: string, enabled: boolean): ReportCardSelection {- const { hasSelection, isDismissing, isResolving, isUnassigning } = useValues(inboxBulkActionsLogic)+ const { hasSelection, isClaiming, isDismissing, isResolving, isUnassigning } = useValues(inboxBulkActionsLogic)const { toggleReportSelection, selectRange } = useActions(inboxBulkActionsLogic)// Only this row's own flag, not the id list: reading the list subscribed every card to every// other card's selection, so picking one row repainted the whole inbox. The booleans above@@ -48,7 +48,7 @@ export function useReportCardSelection(reportId: string, enabled: boolean): Repoconst isReportSelected: boolean = useSelector((state) =>inboxBulkActionsLogic.selectors.selectedReportIds(state).includes(reportId))- const selectionDisabled = isDismissing || isResolving || isUnassigning+ const selectionDisabled = isClaiming || isDismissing || isResolving || isUnassigningconst holdTimerRef = useRef<number | null>(null)const holdOriginRef = useRef<{ x: number; y: number } | null>(null)diff --git a/products/signals/frontend/inbox/components/shell/InboxBulkSelectionBar.test.tsx b/products/signals/frontend/inbox/components/shell/InboxBulkSelectionBar.test.tsxindex 6010b74ea15e..0a2233dd2bb8 100644--- a/products/signals/frontend/inbox/components/shell/InboxBulkSelectionBar.test.tsx+++ b/products/signals/frontend/inbox/components/shell/InboxBulkSelectionBar.test.tsx@@ -6,6 +6,7 @@ import { expectLogic } from 'kea-test-utils'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'+import { teammateClaim } from '../../__mocks__/inboxMocks'import { inboxBulkActionsLogic } from '../../logics/inboxBulkActionsLogic'import { inboxFiltersLogic } from '../../logics/inboxFiltersLogic'import { INBOX_SCOPE_ENTIRE_PROJECT, INBOX_SCOPE_FOR_YOU, type SignalReport, SignalReportStatus } from '../../types'@@ -110,4 +111,30 @@ describe('InboxBulkSelectionBar', () => {.toMatchValues({ selectedReportIds: [] })expect(deleted.sort()).toEqual(sent)})++ // A report a person holds must not reach the server, and the whole selection must go in one request.+ it('claims only the claimable reports, in one request', async () => {+ const bodies: unknown[] = []+ useMocks({+ post: {+ '/api/projects/:team_id/signals/reports/bulk_claim/': async ({ request }) => {+ bodies.push(await request.json())+ return [200, { results: [], claimed_count: 2, conflict_count: 0, not_found_count: 0 }]+ },+ },+ })+ logic.actions.setSelectedReportIds(['a', 'b', 'c'])+ render(+ <InboxBulkSelectionBar+ reports={[makeReport('a'), makeReport('b', { assignee: teammateClaim }), makeReport('c')]}+ />+ )++ await expectLogic(logic, () => {+ fireEvent.click(screen.getByText('Claim'))+ })+ .toDispatchActions(['bulkClaimSuccess'])+ .toMatchValues({ selectedReportIds: [], isClaiming: false })+ expect(bodies).toEqual([{ ids: ['a', 'c'], takeover_agent_claims: true }])+ })})diff --git a/products/signals/frontend/inbox/components/shell/InboxBulkSelectionBar.tsx b/products/signals/frontend/inbox/components/shell/InboxBulkSelectionBar.tsxindex 6f710ffaa12b..eaceb69fa1d2 100644--- a/products/signals/frontend/inbox/components/shell/InboxBulkSelectionBar.tsx+++ b/products/signals/frontend/inbox/components/shell/InboxBulkSelectionBar.tsx@@ -1,32 +1,33 @@import { useActions, useValues } from 'kea'-import { IconCheckCircle, IconHide, IconLeave, IconX } from '@posthog/icons'+import { IconCheckCircle, IconHide, IconLeave, IconPerson, IconX } from '@posthog/icons'import { LemonButton, LemonMenu } from '@posthog/lemon-ui'import { inboxBulkActionsLogic } from '../../logics/inboxBulkActionsLogic'import { inboxFiltersLogic } from '../../logics/inboxFiltersLogic'import { SignalReport, SignalReportStatus } from '../../types'import { canUnassignMe, hasOpenImplementationPr } from '../../utils/reportActions'+import { isReportClaimable } from '../../utils/reportClaim'import { reviewerRemovalReasonOptions } from '../../utils/reviewerRemovalReasons'import { openDismissReportDialog } from './DismissReportDialog'import { openResolveReportDialog } from './ResolveReportDialog'/*** Bulk action toolbar shown when one or more reports are multi-selected.- * Mirrors desktop `InboxBulkSelectionBar` (the dismiss + clear slice) plus Resolve and Unassign me.+ * Mirrors desktop `InboxBulkSelectionBar` (the dismiss + clear slice) plus Claim, Resolve and Unassign me.* Selection and the bulk state calls live in `inboxBulkActionsLogic`; delete / reingest* remain on `inboxSceneLogic` per-report.*/export function InboxBulkSelectionBar({ reports }: { reports: SignalReport[] }): JSX.Element | null {- const { selectedCount, selectedReportIds, isDismissing, isResolving, isUnassigning } =+ const { selectedCount, selectedReportIds, isClaiming, isDismissing, isResolving, isUnassigning } =useValues(inboxBulkActionsLogic)- const { clearSelection, bulkDismiss, bulkResolve, bulkUnassignMe } = useActions(inboxBulkActionsLogic)+ const { clearSelection, bulkClaim, bulkDismiss, bulkResolve, bulkUnassignMe } = useActions(inboxBulkActionsLogic)const { isScopedToMe } = useValues(inboxFiltersLogic)if (selectedCount === 0) {return null}- const busy = isDismissing || isResolving || isUnassigning+ const busy = isClaiming || isDismissing || isResolving || isUnassigningconst selectedIds = new Set(selectedReportIds)const selectedReports = reports.filter((report) => selectedIds.has(report.id))const isMonitoring =@@ -36,6 +37,7 @@ export function InboxBulkSelectionBar({ reports }: { reports: SignalReport[] }):const unassignableIds = reports.filter((report) => selectedIds.has(report.id) && canUnassignMe(report, isScopedToMe)).map((report) => report.id)+ const claimableIds = selectedReports.filter(isReportClaimable).map((report) => report.id)return (<div className="flex items-center justify-between gap-3 flex-wrap rounded border border-accent bg-accent-highlight-secondary px-3 py-2">@@ -45,6 +47,23 @@ export function InboxBulkSelectionBar({ reports }: { reports: SignalReport[] }):</div><div className="flex items-center gap-2 flex-wrap">+ <LemonButton+ type="secondary"+ size="small"+ icon={<IconPerson />}+ loading={isClaiming}+ disabledReason={+ busy+ ? 'Working…'+ : claimableIds.length === 0+ ? 'None of the selected reports can be claimed'+ : undefined+ }+ onClick={() => bulkClaim(claimableIds)}+ data-attr="inbox-bulk-claim"+ >+ Claim+ </LemonButton><LemonButtontype="secondary"size="small"diff --git a/products/signals/frontend/inbox/logics/inboxBulkActionsLogic.test.ts b/products/signals/frontend/inbox/logics/inboxBulkActionsLogic.test.tsindex 15c426231dd3..72cf9732b450 100644--- a/products/signals/frontend/inbox/logics/inboxBulkActionsLogic.test.ts+++ b/products/signals/frontend/inbox/logics/inboxBulkActionsLogic.test.ts@@ -1,7 +1,11 @@+/* oxlint-disable react-hooks/rules-of-hooks -- useMocks is a test helper, not a React hook */import { expectLogic } from 'kea-test-utils'+import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'+import { signalsReportsBulkClaimBodyIdsMax } from 'products/signals/frontend/generated/api.zod'+import { inboxBulkActionsLogic } from './inboxBulkActionsLogic'describe('inboxBulkActionsLogic', () => {@@ -100,4 +104,23 @@ describe('inboxBulkActionsLogic', () => {selectedReportIds: ['c'],})})++ // The endpoint rejects a request over its id limit, so a larger selection must be split, or nothing is claimed.+ it('claims a selection over the endpoint limit in batches and counts every claim', async () => {+ const batchSizes: number[] = []+ useMocks({+ post: {+ '/api/projects/:team_id/signals/reports/bulk_claim/': async ({ request }) => {+ const { ids } = (await request.json()) as { ids: string[] }+ batchSizes.push(ids.length)+ return [200, { results: [], claimed_count: ids.length, conflict_count: 0, not_found_count: 0 }]+ },+ },+ })+ const reportIds = Array.from({ length: signalsReportsBulkClaimBodyIdsMax + 1 }, (_, index) => `r-${index}`)++ await expectLogic(logic, () => logic.actions.bulkClaim(reportIds)).toDispatchActions(['bulkClaimSuccess'])++ expect(batchSizes).toEqual([signalsReportsBulkClaimBodyIdsMax, 1])+ })})diff --git a/products/signals/frontend/inbox/logics/inboxBulkActionsLogic.ts b/products/signals/frontend/inbox/logics/inboxBulkActionsLogic.tsindex 2b13aa48e7b5..0a7319d4af6e 100644--- a/products/signals/frontend/inbox/logics/inboxBulkActionsLogic.ts+++ b/products/signals/frontend/inbox/logics/inboxBulkActionsLogic.ts@@ -7,10 +7,12 @@ 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'@@ -40,10 +42,23 @@ function formatUnassignSummary({ successCount, failureCount }: BulkActionResult)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 // teamLogichasSelection: boolean+ isClaiming: booleanisDismissing: booleanisResolving: booleanisUnassigning: boolean@@ -55,6 +70,15 @@ export interface inboxBulkActionsLogicValues {// 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}@@ -146,7 +170,7 @@ export type inboxBulkActionsLogicType = MakeLogicType<>/**- * Multi-select + bulk dismiss / resolve / unassign for the inbox report list. Mirrors desktop+ * 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@@ -179,6 +203,11 @@ export const inboxBulkActionsLogic = kea<inboxBulkActionsLogicType>([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 }),@@ -256,6 +285,14 @@ export const inboxBulkActionsLogic = kea<inboxBulkActionsLogicType>([bulkUnassignMeFailure: () => false,},],+ isClaiming: [+ false,+ {+ bulkClaim: () => true,+ bulkClaimSuccess: () => false,+ bulkClaimFailure: () => false,+ },+ ],}),selectors({@@ -429,5 +466,51 @@ export const inboxBulkActionsLogic = kea<inboxBulkActionsLogicType>([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()+ }+ },})),])diff --git a/products/signals/frontend/inbox/logics/reportListLogic.test.ts b/products/signals/frontend/inbox/logics/reportListLogic.test.tsindex 3b7c645c9861..605b9f842a6f 100644--- a/products/signals/frontend/inbox/logics/reportListLogic.test.ts+++ b/products/signals/frontend/inbox/logics/reportListLogic.test.ts@@ -126,6 +126,20 @@ describe('reportListLogic', () => {afterEach(() => logic.unmount())+ // A bulk claim returns no rows, so the lists show its claims only after they reload. A failed request+ // can still have saved some claims on the server.+ it.each(['bulkClaimSuccess', 'bulkClaimFailure'] as const)('reloads the first page after %s', async (end) => {+ const bulkLogic = inboxBulkActionsLogic()+ bulkLogic.mount()+ requestedOffsets = []++ bulkLogic.actions[end]()+ await expectLogic(logic).toFinishAllListeners()++ expect(requestedOffsets).toEqual(['0'])+ bulkLogic.unmount()+ })+it('appends the next server page from the loaded offset, then stops', async () => {logic.actions.loadMore()await expectLogic(logic).toFinishAllListeners()diff --git a/products/signals/frontend/inbox/logics/reportListLogic.ts b/products/signals/frontend/inbox/logics/reportListLogic.tsindex 6134344acd23..cf0e8c8b1b5f 100644--- a/products/signals/frontend/inbox/logics/reportListLogic.ts+++ b/products/signals/frontend/inbox/logics/reportListLogic.ts@@ -1003,6 +1003,9 @@ export const reportListLogic = kea<reportListLogicType>([// the affected reports leave it and the counts settle.[inboxBulkActionsLogic.actionTypes.bulkDismissSuccess]: () => actions.refresh(),[inboxBulkActionsLogic.actionTypes.bulkResolveSuccess]: () => actions.refresh(),+ // A bulk claim reloads after a failure too, because the server can save some claims before it fails.+ [inboxBulkActionsLogic.actionTypes.bulkClaimSuccess]: () => actions.refresh(),+ [inboxBulkActionsLogic.actionTypes.bulkClaimFailure]: () => actions.refresh(),// A single report dismissed, resolved, or refunded elsewhere (e.g. the detail pane) – reconcile// this section against the server so the report leaves its section and joins Resolved or// Dismissed, counts included.diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 8a4828570efd..14ff30054b22 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -110804,6 +110804,40 @@ export namespace Schemas {readonly task_id: string | null;}+ export interface SignalReportBulkClaimRequest {+ /**+ * Report ids to claim for the caller in one call (1–100). Duplicates are de-duplicated. Each id is claimed independently, so a report that cannot be claimed does not block the rest.+ * @minItems 1+ * @maxItems 100+ */+ ids: string[];+ /** Take over a report that an agent or an internal task holds. A report that a person holds directly is never taken over and comes back as a conflict. */+ takeover_agent_claims?: boolean;+ }++ export interface SignalReportBulkClaimResult {+ /** The report id this result refers to. */+ id: string;+ /** One of: claimed, conflict, not_found. claimed: the caller holds the claim, including when it already did. conflict: the claim was refused, because someone else holds the report or its status does not allow a claim (a 409 on the single-report endpoint). not_found: no report with this id is visible to you. */+ outcome: string;+ /**+ * Human-readable explanation for a conflict or not_found outcome.+ * @nullable+ */+ detail?: string | null;+ }++ export interface SignalReportBulkClaimResponse {+ /** One result per requested id, in request order (after de-duplication). */+ results: SignalReportBulkClaimResult[];+ /** Number of reports the caller now holds. */+ claimed_count: number;+ /** Number of reports whose claim was refused. */+ conflict_count: number;+ /** Number of requested ids not visible to the caller. */+ not_found_count: number;+ }+/*** * `suppressed` - suppressed* * `potential` - potential