: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): ask before taking over a teammate's inbox claim (#125863)
Dylan Martin520fa5d94747
diff --git a/frontend/src/lib/components/NotificationsMenu/NotificationRow.tsx b/frontend/src/lib/components/NotificationsMenu/NotificationRow.tsxindex 37d6299dec29..f23cbc64d4cc 100644--- a/frontend/src/lib/components/NotificationsMenu/NotificationRow.tsx+++ b/frontend/src/lib/components/NotificationsMenu/NotificationRow.tsx@@ -89,6 +89,10 @@ export const REALTIME_NOTIFICATION_TYPE_META: Record<string, { label: string; delabel: 'First Self-Driving investigation',description: 'When your first Self-Driving investigation finishes, including when it has no report.',},+ report_claim_taken_over: {+ label: 'Self-Driving report takeovers',+ description: 'When someone takes over a Self-Driving report you were working on',+ },feature_flag_failure: {label: 'Feature flag failures',description: 'When a feature flag in your project fails to evaluate',diff --git a/frontend/src/lib/components/NotificationsMenu/notificationToasts.tsx b/frontend/src/lib/components/NotificationsMenu/notificationToasts.tsxindex e75cd1fd9df4..269b8f7e9f93 100644--- a/frontend/src/lib/components/NotificationsMenu/notificationToasts.tsx+++ b/frontend/src/lib/components/NotificationsMenu/notificationToasts.tsx@@ -10,6 +10,7 @@ import {IconFlask,IconFolder,IconNotification,+ IconPerson,IconPieChart,IconPlug,IconSparkles,@@ -44,6 +45,7 @@ const NOTIFICATION_TYPE_ICONS: Record<string, { Icon: ComponentType<{ className?warehouse_suggestion_assigned: { Icon: IconDatabase, color: 'text-primary' },feature_flag_failure: { Icon: IconToggle, color: 'text-danger' },first_report_completed: { Icon: IconSparkles, color: 'text-success' },+ report_claim_taken_over: { Icon: IconPerson, color: 'text-primary' },}export function getNotificationIcon(notificationType: string, className: string = 'size-5'): JSX.Element {diff --git a/products/notifications/backend/facade/enums.py b/products/notifications/backend/facade/enums.pyindex 958081fc495d..78c84debf58c 100644--- a/products/notifications/backend/facade/enums.py+++ b/products/notifications/backend/facade/enums.py@@ -26,6 +26,7 @@ class NotificationType(str, Enum):WAREHOUSE_SUGGESTION_ASSIGNED = "warehouse_suggestion_assigned"FEATURE_FLAG_FAILURE = "feature_flag_failure"FIRST_REPORT_COMPLETED = "first_report_completed"+ REPORT_CLAIM_TAKEN_OVER = "report_claim_taken_over"class Priority(str, Enum):diff --git a/products/signals/backend/claim_takeover_notification.py b/products/signals/backend/claim_takeover_notification.pynew file mode 100644index 000000000000..aa16afa7fd83--- /dev/null+++ b/products/signals/backend/claim_takeover_notification.py@@ -0,0 +1,74 @@+from celery import shared_task++from posthog.exceptions_capture import capture_exception+from posthog.models import Team, User+from posthog.models.scoping import with_team_scope++from products.notifications.backend.facade.api import (+ NotificationData,+ NotificationType,+ TargetType,+ create_notification,+)+from products.signals.backend.artefact_attribution import ArtefactAttribution+from products.signals.backend.claim_display_name import claim_display_name+from products.signals.backend.models import SignalReport+from products.signals.backend.report_access import may_read_reports+from products.signals.backend.report_claims import ReportClaim++_TITLE_SUFFIX = " took over a report you were working on"+# NotificationEvent.title is a varchar(255), and an MCP client name alone can run to 200 characters.+_DISPLAY_NAME_LIMIT = 255 - len(_TITLE_SUFFIX)+++def _takeover_title(display_name: str) -> str:+ # Cut by raw length: Django's Truncator skips combining marks when it counts, so a name built from them+ # could still overflow the column and fail every delivery attempt.+ if len(display_name) > _DISPLAY_NAME_LIMIT:+ display_name = display_name[: _DISPLAY_NAME_LIMIT - 1] + "…"+ return f"{display_name}{_TITLE_SUFFIX}"+++def notify_claim_taken_over(*, report: SignalReport, previous: ReportClaim, actor: ArtefactAttribution) -> None:+ """Queue the notification for the person whose claim was taken over. Call after the takeover commits."""+ if previous.actor_user_id is None:+ return+ try:+ # Delivery evaluates a remote flag, so a bulk takeover must not wait on it once per report.+ send_claim_takeover_notification.delay(+ team_id=report.team_id,+ report_id=str(report.id),+ recipient_id=previous.actor_user_id,+ previous_claim_id=str(previous.claim_id),+ title=_takeover_title(claim_display_name(report, actor)),+ )+ except Exception as error:+ capture_exception(error)+++@shared_task(ignore_result=True, autoretry_for=(Exception,), retry_backoff=True, max_retries=3)+@with_team_scope()+def send_claim_takeover_notification(+ team_id: int, report_id: str, recipient_id: int, previous_claim_id: str, title: str+) -> None:+ report = SignalReport.objects.filter(team_id=team_id, id=report_id).only("id", "team_id", "title").first()+ recipient = User.objects.filter(id=recipient_id, is_active=True).first()+ if report is None or recipient is None:+ return+ # The notification carries the report title, so a recipient who lost Inbox access must not get it.+ if not may_read_reports(user=recipient, team=Team.objects.get(id=team_id)):+ return+ create_notification(+ NotificationData(+ team_id=team_id,+ notification_type=NotificationType.REPORT_CLAIM_TAKEN_OVER,+ title=title,+ body=report.title or "",+ target_type=TargetType.USER,+ target_id=str(recipient_id),+ # Keeps the activity panel from folding takeovers of different reports into one group.+ resource_id=report_id,+ source_url=f"/project/{team_id}/inbox/reports/{report_id}",+ idempotency_key=f"report-claim-taken-over:{previous_claim_id}",+ )+ )diff --git a/products/signals/backend/report_assignments.py b/products/signals/backend/report_assignments.pyindex 483e63d9f646..55a1f6ff39b1 100644--- a/products/signals/backend/report_assignments.py+++ b/products/signals/backend/report_assignments.py@@ -23,6 +23,7 @@ from posthog.models.user import Userfrom products.signals.backend.artefact_attribution import ArtefactAttributionfrom products.signals.backend.artefact_schemas import Dismissal, TaskRunArtefact, WorkClaim, WorkReleasefrom products.signals.backend.claim_display_name import claim_display_name+from products.signals.backend.claim_takeover_notification import notify_claim_taken_overfrom products.signals.backend.models import (InvalidStatusTransition,SignalReport,@@ -405,6 +406,19 @@ def _apply_pr_report_state(report: SignalReport, pr_state: str | None, *, merged)+def _held_by_another_person(claim: ReportClaim, user: User) -> bool:+ # Task claims are left out: auto-start runs tasks as a suggested reviewer who never took the work on.+ return claim.actor_kind in ("user", "agent") and claim.actor_user_id not in (None, user.id)+++def _claim_holder(claim: ReportClaim) -> ArtefactAttribution:+ if claim.actor_kind == "agent" and claim.actor_user_id is not None:+ return ArtefactAttribution.from_agent(claim.actor_user_id, claim.actor_agent or "")+ if claim.actor_user_id is not None:+ return ArtefactAttribution.from_user(claim.actor_user_id)+ return ArtefactAttribution.system()++def claim_report(*,report: SignalReport,@@ -476,6 +490,18 @@ def claim_report(raise ReportClaimConflict("This report already has an active claim. Use takeover=true to take ownership.")+ if _held_by_another_person(assignment, user):+ # takeover_claim_id shows the caller read who holds the claim, so an agent cannot take a+ # teammate's work with a bare takeover=true.+ if not takeover_claim_id:+ holder = claim_display_name(locked_report, _claim_holder(assignment))+ raise ReportClaimConflict(+ f"{holder} is working on this report. Check with your user before you take it over, "+ f"then send takeover=true with takeover_claim_id={assignment.claim_id}."+ )+ transaction.on_commit(+ partial(notify_claim_taken_over, report=locked_report, previous=assignment, actor=actor)+ )release_claim(assignment, actor, takeover=True)assignment = Nonetook_over = Truediff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.pyindex 3b85fc7db33b..d8e6cb09deb2 100644--- a/products/signals/backend/serializers.py+++ b/products/signals/backend/serializers.py@@ -872,7 +872,8 @@ class SignalReportClaimSerializer(serializers.Serializer):required=False,help_text=("With takeover, the claim the caller expects to replace. The takeover is rejected when a different "- "claim is active, so a takeover based on a stale read cannot replace a newer claim."+ "claim is active, so a takeover based on a stale read cannot replace a newer claim. Required to take "+ "over a claim that another person holds, directly or through their agent. That person is notified."),)pr_url = serializers.URLField(diff --git a/products/signals/backend/tasks.py b/products/signals/backend/tasks.pyindex 30a4a5c09e8c..5a0dbd3377b0 100644--- a/products/signals/backend/tasks.py+++ b/products/signals/backend/tasks.py@@ -33,6 +33,9 @@ from posthog.temporal.common.utils import is_stale_connection_read_only_errorfrom products.signals.backend import report_assignmentsfrom products.signals.backend.assignment_flags import assignment_side_effects_allowedfrom products.signals.backend.billing import current_billing_period_bounds+from products.signals.backend.claim_takeover_notification import (+ send_claim_takeover_notification as send_claim_takeover_notification,+)from products.signals.backend.first_report_notification_tasks import (dispatch_first_report_notification as dispatch_first_report_notification,sweep_first_report_notifications as sweep_first_report_notifications,diff --git a/products/signals/backend/test/test_signal_report_assignment_api.py b/products/signals/backend/test/test_signal_report_assignment_api.pyindex a0fce43f27f0..47480e957915 100644--- a/products/signals/backend/test/test_signal_report_assignment_api.py+++ b/products/signals/backend/test/test_signal_report_assignment_api.py@@ -610,6 +610,71 @@ class TestSignalReportAssignmentAPI(APIBaseTest):claim = SignalReportArtefact.objects.get(report=report, type="work_claim")assert json.loads(claim.content)["display_name"] == expected+ @parameterized.expand(+ [+ ("agent_without_claim_id", "codex", False, status.HTTP_409_CONFLICT, SignalActorKind.USER),+ ("agent_with_claim_id", "codex", True, status.HTTP_200_OK, SignalActorKind.AGENT),+ ("agent_with_overlong_client_name", "c" * 200, True, status.HTTP_200_OK, SignalActorKind.AGENT),+ # Combining marks hide most of the length from a character count, so the cap must use the raw length.+ ("agent_with_combining_marks", "q\u0301" * 100, True, status.HTTP_200_OK, SignalActorKind.AGENT),+ ("person_with_claim_id", None, True, status.HTTP_200_OK, SignalActorKind.USER),+ # The notification carries the report title, so someone who lost Inbox access gets none.+ ("holder_without_inbox_access", None, True, status.HTTP_200_OK, SignalActorKind.USER),+ ]+ )+ @patch("products.signals.backend.claim_takeover_notification.create_notification")+ def test_taking_over_another_persons_claim_needs_claim_id_and_notifies_them(+ self,+ name: str,+ agent: str | None,+ send_claim_id: bool,+ expected_status: int,+ expected_kind: str,+ mock_create_notification: MagicMock,+ ):+ report = self._create_report(title="Checkout fails")+ teammate = User.objects.create_and_join(self.organization, "[email protected]", None, first_name="Dana")+ self.client.force_login(teammate)+ teammate_claim = self.client.post(self._claim_url(report), data={}, format="json").json()["assignee"]+ if name == "agent_with_combining_marks":+ self.user.first_name = "F" * 60+ self.user.save(update_fields=["first_name"])+ self.client.force_login(self.user)++ data: dict[str, object] = {"takeover": True}+ if send_claim_id:+ data["takeover_claim_id"] = teammate_claim["claim_id"]+ with (+ patch(+ "products.signals.backend.claim_takeover_notification.may_read_reports",+ return_value=name != "holder_without_inbox_access",+ ),+ self.captureOnCommitCallbacks(execute=True),+ ):+ response = self.client.post(+ self._claim_url(report),+ data=data,+ format="json",+ headers=self._agent_headers(agent) if agent else None,+ )++ assert response.status_code == expected_status+ assignment = get_active_claim(team_id=self.team.id, report_id=report.id)+ assert assignment is not None+ assert assignment.actor_kind == expected_kind+ if expected_status == status.HTTP_409_CONFLICT:+ assert "Dana is working on this report" in response.json()["detail"]+ assert assignment.actor_user_id == teammate.id+ mock_create_notification.assert_not_called()+ elif name == "holder_without_inbox_access":+ mock_create_notification.assert_not_called()+ else:+ mock_create_notification.assert_called_once()+ notification = mock_create_notification.call_args.args[0]+ assert notification.target_id == str(teammate.id)+ assert notification.body == "Checkout fails"+ assert len(notification.title) <= 255+def test_claimants_own_task_works_under_their_claim(self):Task = apps.get_model("tasks", "Task")report = self._create_report()diff --git a/products/signals/backend/views.py b/products/signals/backend/views.pyindex 9cce6fac6c08..8fdd81f23f16 100644--- a/products/signals/backend/views.py+++ b/products/signals/backend/views.py@@ -3058,7 +3058,12 @@ class SignalReportViewSet(responses={200: OpenApiResponse(response=SignalReportSerializer, description="Current report and assignment."),400: OpenApiResponse(description="The pull request URL or request shape is invalid."),- 409: OpenApiResponse(description="The report cannot be claimed or released in its current state."),+ 409: OpenApiResponse(+ description=(+ "The report cannot be claimed or released in its current state, or another person holds the "+ "claim and the takeover has no takeover_claim_id."+ )+ ),},summary="Claim or release a signal report",description=(diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex 3ccab7c18920..7d47b223fcfa 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -3260,7 +3260,7 @@ export interface SignalReportClaimApi {pull_requests?: string[]/** Explicitly end another actor's claim and take ownership. */takeover?: boolean- /** With takeover, the claim the caller expects to replace. The takeover is rejected when a different claim is active, so a takeover based on a stale read cannot replace a newer claim. */+ /** With takeover, the claim the caller expects to replace. The takeover is rejected when a different claim is active, so a takeover based on a stale read cannot replace a newer claim. Required to take over a claim that another person holds, directly or through their agent. That person is notified. */takeover_claim_id?: string/** Compatibility alias for adding one PR. Prefer pull_requests for new callers. */pr_url?: stringdiff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.tsindex 4d1ac39504f0..911206ecf22d 100644--- a/products/signals/frontend/generated/api.zod.ts+++ b/products/signals/frontend/generated/api.zod.ts@@ -1128,7 +1128,7 @@ export const SignalsReportsClaimBody = /* @__PURE__ */ zod.object({.uuid().optional().describe(- 'With takeover, the claim the caller expects to replace. The takeover is rejected when a different claim is active, so a takeover based on a stale read cannot replace a newer claim.'+ 'With takeover, the claim the caller expects to replace. The takeover is rejected when a different claim is active, so a takeover based on a stale read cannot replace a newer claim. Required to take over a claim that another person holds, directly or through their agent. That person is notified.'),pr_url: zod.url()diff --git a/products/signals/frontend/inbox/components/cards/ReportContextMenu.test.tsx b/products/signals/frontend/inbox/components/cards/ReportContextMenu.test.tsxindex 5514f681d45d..85f32ccb226d 100644--- a/products/signals/frontend/inbox/components/cards/ReportContextMenu.test.tsx+++ b/products/signals/frontend/inbox/components/cards/ReportContextMenu.test.tsx@@ -9,8 +9,9 @@ import { copyToClipboard } from 'lib/utils/copyToClipboard'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'-import { myAgentClaim, myClaim, teammateClaim } from '../../__mocks__/inboxMocks'+import { agentClaim, myAgentClaim, myClaim, teammateClaim } from '../../__mocks__/inboxMocks'import { inboxFiltersLogic } from '../../logics/inboxFiltersLogic'+import { reportListLogic, sectionListLogicProps } from '../../logics/reportListLogic'import { INBOX_SCOPE_ENTIRE_PROJECT, SignalReport, SignalReportStatus } from '../../types'import { ReportContextMenu } from './ReportContextMenu'@@ -197,12 +198,26 @@ describe('ReportContextMenu', () => {}})- it('does not let the user claim a report a teammate is working on', () => {- openMenu(makeReport({ assignee: teammateClaim }))+ // A silent takeover would move a teammate's work to the user without the teammate knowing.+ it.each([+ { holder: 'a teammate', assignee: teammateClaim, description: 'Robin is working on this report.' },+ {+ holder: "a teammate's agent",+ assignee: agentClaim(teammateClaim.user!, 'codex'),+ description: "Robin's agent is working on this report.",+ },+ ])('asks before it takes over a report $holder is working on', async ({ assignee, description }) => {+ // The list keeps its logic mounted after the menu closes for the dialog.+ reportListLogic(sectionListLogicProps('needs-decision')).mount()+ openMenu(makeReport({ assignee }))- fireEvent.click(screen.getByText('Claim'))+ fireEvent.click(screen.getByText('Take over'))+ expect(await screen.findByText(new RegExp(description))).toBeInTheDocument()expect(claimRequests).toEqual([])+ fireEvent.click(screen.getAllByText('Take over').at(-1)!)++ await waitFor(() => expect(claimRequests).toEqual([{ reportId: 'report-1', body: { takeover: true } }]))})// A relative or wrong-tab URL would copy a link that 404s or opens the wrong list when pasted.diff --git a/products/signals/frontend/inbox/components/cards/ReportContextMenu.tsx b/products/signals/frontend/inbox/components/cards/ReportContextMenu.tsxindex e641ecae0032..b3325cba627b 100644--- a/products/signals/frontend/inbox/components/cards/ReportContextMenu.tsx+++ b/products/signals/frontend/inbox/components/cards/ReportContextMenu.tsx@@ -30,7 +30,6 @@ import {ContextMenuTrigger,} from 'lib/ui/ContextMenu/ContextMenu'import { copyToClipboard } from 'lib/utils/copyToClipboard'-import { fullNameOrEmail } from 'lib/utils/strings'import { userLogic } from 'scenes/userLogic'import { captureInboxReportAction } from '../../inboxAnalytics'@@ -54,12 +53,13 @@ import {canUnassignMe,hasOpenImplementationPr,} from '../../utils/reportActions'-import { isReportClaimable, reportClaimant } from '../../utils/reportClaim'+import { isReportClaimable, reportClaimant, teammateClaimHolder } from '../../utils/reportClaim'import { displayConventionalCommitTitle } from '../../utils/reportPresentation'import { reviewerRemovalReasonOptions } from '../../utils/reviewerRemovalReasons'import { ReviewerSearchList } from '../detail/ReviewerSearchList'import { openDismissReportDialog } from '../shell/DismissReportDialog'import { openResolveReportDialog } from '../shell/ResolveReportDialog'+import { openTakeOverReportDialog } from '../shell/TakeOverReportDialog'import { ReasonSubmenuItems } from './ReasonSubmenuItems'import { useReportCardSelection } from './useReportCardSelection'@@ -170,28 +170,44 @@ function ReportContextMenuItems({</ContextMenuItem>)- // A teammate's claim shows disabled with their name, so the menu says why it can't be taken.+ const currentUserUuid = user?.uuid ?? nullconst claimant = reportClaimant(report)- const isMyClaim = !!claimant && !!user?.uuid && claimant.uuid === user.uuid- const claimDisabledReason = claimSavingReportIds.includes(report.id)- ? 'Updating…'- : claimant && !isMyClaim- ? `${fullNameOrEmail(claimant)} is working on this report`- : null- const claimItem =- claimant || isReportClaimable(report) ? (- <ContextMenuItem asChild disabled={!!claimDisabledReason}>- <ButtonPrimitive- menuItem- onClick={() => setReportClaimed(report, !isMyClaim, 'context_menu')}- disabledReasons={claimDisabledReason ? { [claimDisabledReason]: true } : undefined}- data-attr={isMyClaim ? 'inbox-report-context-menu-unclaim' : 'inbox-report-context-menu-claim'}- >- <IconPerson />- {isMyClaim ? 'Unclaim' : 'Claim'}- </ButtonPrimitive>- </ContextMenuItem>- ) : null+ const isMyClaim = !!claimant && claimant.uuid === currentUserUuid+ const teammate = teammateClaimHolder(report, currentUserUuid)+ const claimSaving = claimSavingReportIds.includes(report.id)++ const claimItem = teammate ? (+ <ContextMenuItem asChild disabled={claimSaving}>+ <ButtonPrimitive+ menuItem+ onClick={() => {+ onOpenDialog()+ openTakeOverReportDialog({+ report,+ holder: teammate,+ onConfirm: () => setReportClaimed(report, true, 'context_menu', true),+ })+ }}+ disabledReasons={claimSaving ? { 'Updating…': true } : undefined}+ data-attr="inbox-report-context-menu-takeover"+ >+ <IconPerson />+ Take over+ </ButtonPrimitive>+ </ContextMenuItem>+ ) : claimant || isReportClaimable(report, currentUserUuid) ? (+ <ContextMenuItem asChild disabled={claimSaving}>+ <ButtonPrimitive+ menuItem+ onClick={() => setReportClaimed(report, !isMyClaim, 'context_menu')}+ disabledReasons={claimSaving ? { 'Updating…': true } : undefined}+ data-attr={isMyClaim ? 'inbox-report-context-menu-unclaim' : 'inbox-report-context-menu-claim'}+ >+ <IconPerson />+ {isMyClaim ? 'Unclaim' : 'Claim'}+ </ButtonPrimitive>+ </ContextMenuItem>+ ) : nullconst dismissWith = (dismissal: DismissalFeedback): void => {const { reason, note, correctedRepository } = dismissaldiff --git a/products/signals/frontend/inbox/components/detail/ReportDetailActions.tsx b/products/signals/frontend/inbox/components/detail/ReportDetailActions.tsxindex 211f3d22eff0..83cc7b202db3 100644--- a/products/signals/frontend/inbox/components/detail/ReportDetailActions.tsx+++ b/products/signals/frontend/inbox/components/detail/ReportDetailActions.tsx@@ -2,7 +2,7 @@ import { useActions, useValues } from 'kea'import { router } from 'kea-router'import { type MouseEvent, useState } from 'react'-import { IconCheckCircle, IconHide, IconReceipt, IconUndo, IconClock } from '@posthog/icons'+import { IconCheckCircle, IconHide, IconReceipt, IconUndo, IconClock, IconPerson } from '@posthog/icons'import { lemonToast } from '@posthog/lemon-ui'import { urls } from 'scenes/urls'@@ -18,6 +18,7 @@ import { hasMergedReportPullRequest } from '../../utils/reportPullRequests'import { setReportState } from '../../utils/writeTimeout'import { useReportDismiss } from '../cards/useReportDismiss'import { useReportRefund } from '../cards/useReportRefund'+import { openTakeOverReportDialog } from '../shell/TakeOverReportDialog'import { useReportResolve } from './useReportResolve'/**@@ -40,8 +41,8 @@ export interface ReportDetailAction {export function useReportDetailActions(report: SignalReport): ReportDetailAction[] {const detailLogic = inboxReportDetailLogic({ reportId: report.id, report })- const { changeReportState } = useActions(detailLogic)- const { reportStateSaving, reportChecks } = useValues(detailLogic)+ const { changeReportState, setReportClaimed } = useActions(detailLogic)+ const { reportStateSaving, reportChecks, teammateClaimHolder, claimSaving } = useValues(detailLogic)const { reportStateChanged, reportWriteFailed } = useActions(inboxBulkActionsLogic)const { activeTab } = useValues(inboxSceneLogic)const { loadSelectedReport } = useActions(inboxSceneLogic)@@ -183,6 +184,23 @@ export function useReportDetailActions(report: SignalReport): ReportDetailAction}const actions: ReportDetailAction[] = [+ ...(teammateClaimHolder+ ? [+ {+ key: 'takeover',+ label: 'Take over',+ icon: <IconPerson />,+ loading: claimSaving,+ tooltip: 'Take over the claim to work on this report',+ onClick: () =>+ openTakeOverReportDialog({+ report,+ holder: teammateClaimHolder,+ onConfirm: () => setReportClaimed(true, true, report.assignee),+ }),+ },+ ]+ : []),...(canMonitorReport(report, (reportChecks?.length ?? 0) > 0)? [{diff --git a/products/signals/frontend/inbox/components/shell/InboxBulkSelectionBar.tsx b/products/signals/frontend/inbox/components/shell/InboxBulkSelectionBar.tsxindex eaceb69fa1d2..dcdc038b0cf9 100644--- a/products/signals/frontend/inbox/components/shell/InboxBulkSelectionBar.tsx+++ b/products/signals/frontend/inbox/components/shell/InboxBulkSelectionBar.tsx@@ -3,6 +3,8 @@ import { useActions, useValues } from 'kea'import { IconCheckCircle, IconHide, IconLeave, IconPerson, IconX } from '@posthog/icons'import { LemonButton, LemonMenu } from '@posthog/lemon-ui'+import { userLogic } from 'scenes/userLogic'+import { inboxBulkActionsLogic } from '../../logics/inboxBulkActionsLogic'import { inboxFiltersLogic } from '../../logics/inboxFiltersLogic'import { SignalReport, SignalReportStatus } from '../../types'@@ -23,6 +25,7 @@ export function InboxBulkSelectionBar({ reports }: { reports: SignalReport[] }):useValues(inboxBulkActionsLogic)const { clearSelection, bulkClaim, bulkDismiss, bulkResolve, bulkUnassignMe } = useActions(inboxBulkActionsLogic)const { isScopedToMe } = useValues(inboxFiltersLogic)+ const { user } = useValues(userLogic)if (selectedCount === 0) {return null@@ -37,7 +40,9 @@ 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)+ const claimableIds = selectedReports+ .filter((report) => isReportClaimable(report, user?.uuid ?? null))+ .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">diff --git a/products/signals/frontend/inbox/components/shell/TakeOverReportDialog.tsx b/products/signals/frontend/inbox/components/shell/TakeOverReportDialog.tsxnew file mode 100644index 000000000000..4816dab2b6a9--- /dev/null+++ b/products/signals/frontend/inbox/components/shell/TakeOverReportDialog.tsx@@ -0,0 +1,29 @@+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'+import { fullNameOrEmail } from 'lib/utils/strings'++import type { _UserApi } from 'products/signals/frontend/generated/api.schemas'++import { SignalReport } from '../../types'++interface OpenTakeOverReportDialogParams {+ report: Pick<SignalReport, 'assignee'>+ /** The other person who holds the claim, from `teammateClaimHolder`. */+ holder: _UserApi+ onConfirm: () => void+}++/** Asks before the user takes over a teammate's claim, because the server tells that person their work moved. */+export function openTakeOverReportDialog({ report, holder, onConfirm }: OpenTakeOverReportDialogParams): void {+ const holderName = fullNameOrEmail(holder)+ const holderLabel = report.assignee?.kind === 'agent' ? `${holderName}'s agent` : holderName+ LemonDialog.open({+ title: 'Take over this report?',+ description: `${holderLabel} is working on this report. If you take it over, we let ${holderName} know.`,+ primaryButton: {+ children: 'Take over',+ onClick: onConfirm,+ 'data-attr': 'inbox-report-takeover-confirm',+ },+ secondaryButton: { children: 'Cancel' },+ })+}diff --git a/products/signals/frontend/inbox/logics/inboxReportDetailLogic.test.ts b/products/signals/frontend/inbox/logics/inboxReportDetailLogic.test.tsindex 61975c0a5aa1..f45706282c0f 100644--- a/products/signals/frontend/inbox/logics/inboxReportDetailLogic.test.ts+++ b/products/signals/frontend/inbox/logics/inboxReportDetailLogic.test.ts@@ -508,7 +508,15 @@ describe('inboxReportDetailLogic', () => {responsible_user: null,}) as unknown as NonNullable<SignalReport['assignee']>- it.each([+ it.each<{+ name: string+ serverAssignee: NonNullable<SignalReport['assignee']>+ expectedBodies: unknown[]+ expectedToast: string | null+ shownAssignee?: SignalReport['assignee']+ takeover?: boolean+ confirmedAssignee?: SignalReport['assignee']+ }>([{name: 'takes over the task claim the list row did not show',serverAssignee: claimBy('task', 'claim-task'),@@ -527,48 +535,73 @@ describe('inboxReportDetailLogic', () => {expectedBodies: [{ takeover: false }],expectedToast: 'Someone else is already working on this report.',},- ])('$name', async ({ serverAssignee, expectedBodies, expectedToast }) => {- const myClaim = claimBy('user', 'claim-mine', 'me')- const bodies: unknown[] = []- const claim = jest.fn(async ({ request }: MockResolverInfo): Promise<[number, unknown]> => {- const body = (await request.json()) as { takeover?: boolean }- bodies.push(body)- return body.takeover- ? [200, { ...REPORT, assignee: myClaim, updated_at: '2026-01-02T00:00:00Z' }]- : [409, { detail: 'This report already has an active claim.' }]- })- useMocks({- get: {- '/api/projects/:team_id/signals/reports/:id/feedback_state/': { sentiment: null, note: '' },- '/api/projects/:team_id/signals/reports/:id/artefacts/': { results: [] },- '/api/projects/:team_id/signals/reports/:id/signals/': { signals: [] },- '/api/projects/:team_id/signals/reports/:id/checks/': { results: [] },- '/api/projects/:team_id/signals/reports/available_reviewers/': [],- '/api/projects/:team_id/signals/reports/:id/': { ...REPORT, assignee: serverAssignee },- },- post: { '/api/projects/:team_id/signals/reports/:id/claim/': claim },- })- initKeaTests()- const errorToast = jest.spyOn(lemonToast, 'error')- const logic = inboxReportDetailLogic({ reportId: REPORT.id, report: { ...REPORT, assignee: null } })- logic.mount()- try {- await expectLogic(logic).toFinishAllListeners()- logic.actions.setReportClaimed(true)- await waitFor(() => expect(logic.values.claimSaving).toBe(false))-- expect(bodies).toEqual(expectedBodies)- if (expectedToast) {- expect(errorToast).toHaveBeenCalledWith(expectedToast)- } else {- expect(errorToast).not.toHaveBeenCalled()- expect(logic.values.report?.assignee).toEqual(myClaim)+ {+ name: "takes over a teammate's claim the person confirmed",+ serverAssignee: claimBy('user', 'claim-person', 'other-user'),+ shownAssignee: claimBy('user', 'claim-person', 'other-user'),+ takeover: true,+ expectedBodies: [{ takeover: true, takeover_claim_id: 'claim-person' }],+ expectedToast: null,+ },+ {+ // The report refreshed to a newer claim while the dialog was open, so the takeover must name the+ // claim the dialog showed and let the server refuse it.+ name: 'takes over only the claim the dialog showed',+ serverAssignee: claimBy('user', 'claim-person', 'other-user'),+ shownAssignee: claimBy('user', 'claim-newer', 'third-user'),+ confirmedAssignee: claimBy('user', 'claim-person', 'other-user'),+ takeover: true,+ expectedBodies: [{ takeover: true, takeover_claim_id: 'claim-person' }],+ expectedToast: null,+ },+ ])(+ '$name',+ async ({ serverAssignee, expectedBodies, expectedToast, shownAssignee, takeover, confirmedAssignee }) => {+ const myClaim = claimBy('user', 'claim-mine', 'me')+ const bodies: unknown[] = []+ const claim = jest.fn(async ({ request }: MockResolverInfo): Promise<[number, unknown]> => {+ const body = (await request.json()) as { takeover?: boolean }+ bodies.push(body)+ return body.takeover+ ? [200, { ...REPORT, assignee: myClaim, updated_at: '2026-01-02T00:00:00Z' }]+ : [409, { detail: 'This report already has an active claim.' }]+ })+ useMocks({+ get: {+ '/api/projects/:team_id/signals/reports/:id/feedback_state/': { sentiment: null, note: '' },+ '/api/projects/:team_id/signals/reports/:id/artefacts/': { results: [] },+ '/api/projects/:team_id/signals/reports/:id/signals/': { signals: [] },+ '/api/projects/:team_id/signals/reports/:id/checks/': { results: [] },+ '/api/projects/:team_id/signals/reports/available_reviewers/': [],+ '/api/projects/:team_id/signals/reports/:id/': { ...REPORT, assignee: serverAssignee },+ },+ post: { '/api/projects/:team_id/signals/reports/:id/claim/': claim },+ })+ initKeaTests()+ const errorToast = jest.spyOn(lemonToast, 'error')+ const logic = inboxReportDetailLogic({+ reportId: REPORT.id,+ report: { ...REPORT, assignee: shownAssignee },+ })+ logic.mount()+ try {+ await expectLogic(logic).toFinishAllListeners()+ logic.actions.setReportClaimed(true, takeover, confirmedAssignee)+ await waitFor(() => expect(logic.values.claimSaving).toBe(false))++ expect(bodies).toEqual(expectedBodies)+ if (expectedToast) {+ expect(errorToast).toHaveBeenCalledWith(expectedToast)+ } else {+ expect(errorToast).not.toHaveBeenCalled()+ expect(logic.values.report?.assignee).toEqual(myClaim)+ }+ } finally {+ errorToast.mockRestore()+ logic.unmount()}- } finally {- errorToast.mockRestore()- logic.unmount()}- })+ )})// A claim from the row menu writes a work-log entry, and a ready report without a running task does not polldiff --git a/products/signals/frontend/inbox/logics/inboxReportDetailLogic.ts b/products/signals/frontend/inbox/logics/inboxReportDetailLogic.tsindex a485e4bcaff9..d0f32d5c500d 100644--- a/products/signals/frontend/inbox/logics/inboxReportDetailLogic.ts+++ b/products/signals/frontend/inbox/logics/inboxReportDetailLogic.ts@@ -72,6 +72,7 @@ import type { SignalNodeApi } from 'products/signals/frontend/generated/api.scheimport type { SignalReportFeedbackSentimentEnumApi } from '../../generated/api.schemas'import type { SignalReportStateEnumApi } from '../../generated/api.schemas'+import type { SignalReportAssigneeApi } from '../../generated/api.schemas'import { deriveTaskPurpose, ReportTaskPurpose, TaskRunArtefactContent } from '../components/detail/artefactTypes'import {AvailableReviewerOption,@@ -89,7 +90,7 @@ import { inboxSceneLogic } from '../inboxSceneLogic'import { ReportDiscussionIntent, inboxTaskKickoffLogic } from '../inboxTaskKickoffLogic'import { EnrichedReviewer, ReviewerRemoval, SignalReport, SignalReportArtefact, SignalReportStatus } from '../types'import { ChartPlacements, resolveChartPlacements } from '../utils/chartPlacement'-import { isReportClaimable, reportClaimant, requestReportClaim } from '../utils/reportClaim'+import { isReportClaimable, reportClaimant, requestReportClaim, teammateClaimHolder } from '../utils/reportClaim'import { reportPullRequests, primaryReportPullRequest, type ReportPullRequest } from '../utils/reportPullRequests'import { withInboxWriteTimeout } from '../utils/writeTimeout'import { inboxBulkActionsLogic } from './inboxBulkActionsLogic'@@ -410,6 +411,7 @@ export interface inboxReportDetailLogicValues {selectedTask: ReportTaskEntry | nullselectedTaskId: string | nullshouldPollReportTasks: boolean+ teammateClaimHolder: _UserApi | nulltrailingCharts: ReportChartApi[]}@@ -724,8 +726,14 @@ export interface inboxReportDetailLogicActions {setReport: (report: SignalReport | null) => {report: SignalReport | null}- setReportClaimed: (claimed: boolean) => {+ setReportClaimed: (+ claimed: boolean,+ takeover?: boolean,+ shownAssignee?: SignalReport['assignee']+ ) => {claimed: boolean+ shownAssignee: SignalReportAssigneeApi | null | undefined+ takeover: boolean}setReportStateSaving: (saving: boolean) => {saving: boolean@@ -821,12 +829,12 @@ export interface inboxReportDetailLogicMeta {isReResearch: (reportTasks: ReportTaskEntry[] | null) => booleanreportClaimant: (report: SignalReport | null) => _UserApi | nullisClaimedByMe: (reportClaimant: _UserApi | null, user: null | import('~/types').UserType) => boolean- isReportClaimable: (report: SignalReport | null) => boolean+ teammateClaimHolder: (report: SignalReport | null, user: null | import('~/types').UserType) => _UserApi | null+ isReportClaimable: (report: SignalReport | null, user: null | import('~/types').UserType) => booleanimplementationSlotClaim: (reportTasks: ReportTaskEntry[] | null) => ImplementationSlotClaim | nullimplementationDisabledReason: (implementationSlotClaim: ImplementationSlotClaim | null,- reportClaimant: _UserApi | null,- isClaimedByMe: boolean+ teammateClaimHolder: _UserApi | null) => string | nullprimaryTask: (reportTasks: ReportTaskEntry[] | null) => ReportTaskEntry | nullreportTaskToOpen: (reportTasks: ReportTaskEntry[] | null) => ReportTaskEntry | null@@ -907,7 +915,11 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([setPrioritySaving: (saving: boolean) => ({ saving }),changeReportState: (state: SignalReportStateRequestApi['state']) => ({ state }),setReportStateSaving: (saving: boolean) => ({ saving }),- setReportClaimed: (claimed: boolean) => ({ claimed }),+ setReportClaimed: (claimed: boolean, takeover: boolean = false, shownAssignee?: SignalReport['assignee']) => ({+ claimed,+ takeover,+ shownAssignee,+ }),setClaimSaving: (saving: boolean) => ({ saving }),// Optimistically replace the reviewer list while the PUT is in flight, then reload from the server.// Addressed by report (not artefact) so a report with no reviewers yet can still be assigned one.@@ -1635,9 +1647,15 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([(claimant: _UserApi | null, user: { uuid: string } | null): boolean =>!!claimant && !!user && claimant.uuid === user.uuid,],+ teammateClaimHolder: [+ (s) => [s.report, userLogic.selectors.user],+ (report: SignalReport | null, user: { uuid: string } | null): _UserApi | null =>+ report ? teammateClaimHolder(report, user?.uuid ?? null) : null,+ ],isReportClaimable: [- (s) => [s.report],- (report: SignalReport | null): boolean => (report ? isReportClaimable(report) : false),+ (s) => [s.report, userLogic.selectors.user],+ (report: SignalReport | null, user: { uuid: string } | null): boolean =>+ report ? isReportClaimable(report, user?.uuid ?? null) : false,],implementationSlotClaim: [(s) => [s.reportTasks],@@ -1645,16 +1663,12 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([implementationSlotClaim(reportTasks),],implementationDisabledReason: [- (s) => [s.implementationSlotClaim, s.reportClaimant, s.isClaimedByMe],- (- slotClaim: ImplementationSlotClaim | null,- claimant: _UserApi | null,- isClaimedByMe: boolean- ): string | null =>+ (s) => [s.implementationSlotClaim, s.teammateClaimHolder],+ (slotClaim: ImplementationSlotClaim | null, holder: _UserApi | null): string | null =>slotClaim? SLOT_CLAIM_DISABLED_REASON[slotClaim]- : claimant && !isClaimedByMe- ? `${fullNameOrEmail(claimant)} is working on this report.`+ : holder+ ? `${fullNameOrEmail(holder)} is working on this report. Take it over to implement it.`: null,],// The default task whose run log is shown: prefer one still in motion, tie-break by most-recent@@ -1764,7 +1778,7 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([actions.loadReportArtefacts()actions.setPrioritySaving(false)},- setReportClaimed: async ({ claimed }) => {+ setReportClaimed: async ({ claimed, takeover, shownAssignee }) => {const teamId = teamLogic.values.currentTeamIdconst currentReport = values.reportif (!teamId || !currentReport || values.claimSaving) {@@ -1775,12 +1789,15 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([report: currentReport,actionType: claimed ? 'claim' : 'unclaim',surface: 'detail_pane',+ extra: takeover ? { takeover: true } : undefined,})const scene = inboxSceneLogic.findMounted()const outcome = await requestReportClaim(String(teamId),- { id: props.reportId, assignee: currentReport.assignee },- claimed+ // A confirmed takeover names the claim the dialog showed, so a claim that changed since is refused.+ { id: props.reportId, assignee: shownAssignee !== undefined ? shownAssignee : currentReport.assignee },+ claimed,+ { currentUserUuid: userLogic.values.user?.uuid ?? null, takeover })if (!outcome.ok) {if (inboxReportDetailLogic.isMounted(props)) {diff --git a/products/signals/frontend/inbox/logics/reportListLogic.ts b/products/signals/frontend/inbox/logics/reportListLogic.tsindex c098445ee494..122ed5e9e04b 100644--- a/products/signals/frontend/inbox/logics/reportListLogic.ts+++ b/products/signals/frontend/inbox/logics/reportListLogic.ts@@ -425,11 +425,13 @@ export interface reportListLogicActions {setReportClaimed: (report: SignalReport,claimed: boolean,- surface: InboxReportActionSurface+ surface: InboxReportActionSurface,+ takeover?: boolean) => {claimed: booleanreport: SignalReportsurface: InboxReportActionSurface+ takeover: boolean}setReportClaimedFinished: (reportId: string) => {reportId: string@@ -587,10 +589,16 @@ export const reportListLogic = kea<reportListLogicType>([reason,}),unassignMeFinished: (reportId: string) => ({ reportId }),- setReportClaimed: (report: SignalReport, claimed: boolean, surface: InboxReportActionSurface) => ({+ setReportClaimed: (+ report: SignalReport,+ claimed: boolean,+ surface: InboxReportActionSurface,+ takeover: boolean = false+ ) => ({report,claimed,surface,+ takeover,}),setReportClaimedFinished: (reportId: string) => ({ reportId }),setSuggestedToMe: (reportIds: string[], isSuggested: boolean) => ({ reportIds, isSuggested }),@@ -1223,9 +1231,17 @@ export const reportListLogic = kea<reportListLogicType>([// The list that started the request can unmount while it runs, for example when triage closes.inboxBulkActionsLogic.findMounted()?.actions.unassignedMe([reportId])},- setReportClaimed: async ({ report, claimed, surface }) => {- captureInboxReportAction({ report, actionType: claimed ? 'claim' : 'unclaim', surface })- const outcome = await requestReportClaim(String(values.currentTeamId), report, claimed)+ setReportClaimed: async ({ report, claimed, surface, takeover }) => {+ captureInboxReportAction({+ report,+ actionType: claimed ? 'claim' : 'unclaim',+ surface,+ extra: takeover ? { takeover: true } : undefined,+ })+ const outcome = await requestReportClaim(String(values.currentTeamId), report, claimed, {+ currentUserUuid: values.user?.uuid ?? null,+ takeover,+ })actions.setReportClaimedFinished(report.id)if (!outcome.ok) {lemonToast.error(outcome.message)diff --git a/products/signals/frontend/inbox/utils/reportClaim.test.ts b/products/signals/frontend/inbox/utils/reportClaim.test.tsindex 761fcdd2bd95..06bcb27cddf5 100644--- a/products/signals/frontend/inbox/utils/reportClaim.test.ts+++ b/products/signals/frontend/inbox/utils/reportClaim.test.ts@@ -4,57 +4,98 @@ import { SignalReportStatus } from '../types'import { isReportClaimable, reportClaimant, reportClaimRequest } from './reportClaim'describe('report claim', () => {- const assignee = (kind: SignalActorKindEnumApi): SignalReportAssigneeApi => ({- claim_id: 'claim-1',- kind,- user: { id: 1, uuid: 'user-1', first_name: 'Bob', last_name: 'Smith', email: '[email protected]' },- task_id: kind === 'task' ? 'task-1' : null,- agent: kind === 'agent' ? 'codex' : null,- claimed_at: '2026-10-22T10:00:00Z',- responsible_user: { id: 1, uuid: 'user-1', first_name: 'Bob', last_name: 'Smith', email: '[email protected]' },- })+ const me = 'user-1'+ const assignee = (kind: SignalActorKindEnumApi, holderUuid: string = me): SignalReportAssigneeApi => {+ const person = { id: 1, uuid: holderUuid, first_name: 'Bob', last_name: 'Smith', email: '[email protected]' }+ return {+ claim_id: 'claim-1',+ kind,+ user: person,+ task_id: kind === 'task' ? 'task-1' : null,+ agent: kind === 'agent' ? 'codex' : null,+ claimed_at: '2026-10-22T10:00:00Z',+ responsible_user: person,+ }+ }+ const takeover = { takeover: true, takeover_claim_id: 'claim-1' }it.each([- { case: 'unclaimed', current: null, claimable: true, claimant: null, request: { takeover: false } },{- case: 'held by a person',+ case: 'unclaimed',+ current: null,+ claimable: true,+ claimant: null,+ request: { takeover: false },+ confirmed: { takeover: false },+ },+ {+ case: 'held by the user',current: assignee('user'),claimable: false,claimant: assignee('user').user,request: { takeover: false },+ confirmed: takeover,},{- case: 'held by an agent',+ case: "held by the user's agent",current: assignee('agent'),claimable: false,claimant: assignee('agent').responsible_user,- request: { takeover: true, takeover_claim_id: 'claim-1' },+ request: takeover,+ confirmed: takeover,},{case: 'held by an agent without a responsible user',current: { ...assignee('agent'), responsible_user: null },claimable: false,claimant: assignee('agent').user,- request: { takeover: true, takeover_claim_id: 'claim-1' },+ request: takeover,+ confirmed: takeover,+ },+ {+ case: "held by a teammate's agent without a responsible user",+ current: { ...assignee('agent', 'user-2'), responsible_user: null },+ claimable: false,+ claimant: assignee('agent', 'user-2').user,+ request: { takeover: false },+ confirmed: takeover,},{case: 'held by a task',- current: assignee('task'),+ current: assignee('task', 'user-2'),claimable: true,claimant: null,- request: { takeover: true, takeover_claim_id: 'claim-1' },+ request: takeover,+ confirmed: takeover,+ },+ {+ case: 'held by a teammate',+ current: assignee('user', 'user-2'),+ claimable: false,+ claimant: assignee('user', 'user-2').user,+ request: { takeover: false },+ confirmed: takeover,+ },+ {+ case: "held by a teammate's agent",+ current: assignee('agent', 'user-2'),+ claimable: false,+ claimant: assignee('agent', 'user-2').responsible_user,+ request: { takeover: false },+ confirmed: takeover,},- ])('claims a report $case', ({ current, claimable, claimant, request }) => {+ ])('claims a report $case', ({ current, claimable, claimant, request, confirmed }) => {const report = { assignee: current, status: SignalReportStatus.READY }- expect(isReportClaimable(report)).toBe(claimable)+ expect(isReportClaimable(report, me)).toBe(claimable)expect(reportClaimant(report)).toEqual(claimant)- expect(reportClaimRequest(report, true)).toEqual(request)+ expect(reportClaimRequest(report, true, { currentUserUuid: me })).toEqual(request)+ expect(reportClaimRequest(report, true, { currentUserUuid: me, takeover: true })).toEqual(confirmed)})it.each([{ status: SignalReportStatus.FAILED, claimable: true },{ status: SignalReportStatus.RESOLVED, claimable: false },])('offers a claim on a $status report: $claimable', ({ status, claimable }) => {- expect(isReportClaimable({ assignee: null, status })).toBe(claimable)+ expect(isReportClaimable({ assignee: null, status }, me)).toBe(claimable)})})diff --git a/products/signals/frontend/inbox/utils/reportClaim.ts b/products/signals/frontend/inbox/utils/reportClaim.tsindex 9672d67e06cc..b7e3ee4e9b46 100644--- a/products/signals/frontend/inbox/utils/reportClaim.ts+++ b/products/signals/frontend/inbox/utils/reportClaim.ts@@ -24,38 +24,70 @@ export function reportClaimant(report: Pick<SignalReport, 'assignee'>): _UserApireturn assignee?.kind === 'user' ? assignee.user : null}-export function isReportClaimable(report: Pick<SignalReport, 'assignee' | 'status'>): boolean {- return CLAIMABLE_STATUSES.has(report.status) && reportClaimant(report) === null+/** The other person who holds the claim, directly or through their agent, or null. */+export function teammateClaimHolder(+ report: Pick<SignalReport, 'assignee'>,+ currentUserUuid: string | null+): _UserApi | null {+ const holder = reportClaimant(report)+ return holder && holder.uuid !== currentUserUuid ? holder : null}-// A person takes over an agent or task claim, because the agent keeps working either way.-export function reportClaimRequest(report: Pick<SignalReport, 'assignee'>, claimed: boolean): SignalReportClaimApi {+export function isReportClaimable(+ report: Pick<SignalReport, 'assignee' | 'status'>,+ currentUserUuid: string | null+): boolean {+ return (+ CLAIMABLE_STATUSES.has(report.status) &&+ reportClaimant(report) === null &&+ teammateClaimHolder(report, currentUserUuid) === null+ )+}++export interface ReportClaimOptions {+ currentUserUuid: string | null+ /** The person confirmed that they take over another person's claim. */+ takeover?: boolean+}++// The user takes over a task claim or their own agent's claim without a prompt, because the agent keeps working+// either way. Another person's claim needs their confirmation, and the server notifies that person.+export function reportClaimRequest(+ report: Pick<SignalReport, 'assignee'>,+ claimed: boolean,+ { currentUserUuid, takeover = false }: ReportClaimOptions+): SignalReportClaimApi {if (!claimed) {return { release: true }}const assignee = report.assignee- if (!assignee || assignee.kind === 'user') {+ const needsConfirmation = assignee?.kind === 'user' || teammateClaimHolder(report, currentUserUuid) !== null+ if (!assignee || (needsConfirmation && !takeover)) {return { takeover: false }}- // Naming the expected claim makes the server refuse the takeover when a person claimed meanwhile.+ // Naming the expected claim makes the server refuse the takeover when someone else claimed meanwhile.return assignee.claim_id ? { takeover: true, takeover_claim_id: assignee.claim_id } : { takeover: true }}type FreshClaimAttempt = { fresh: SignalReportApi | null; updated: SignalReportApi | null }/** Claims again from the server's current record. The page can still show the list's copy, whose claim may be out of date. */-async function claimFromFreshReport(teamId: string, reportId: string): Promise<FreshClaimAttempt> {+async function claimFromFreshReport(+ teamId: string,+ reportId: string,+ currentUserUuid: string | null+): Promise<FreshClaimAttempt> {let fresh: SignalReportApitry {fresh = await withInboxWriteTimeout('claim', (options) => signalsReportsRetrieve(teamId, reportId, options))} catch {return { fresh: null, updated: null }}- if (!isReportClaimable({ status: fresh.status as SignalReportStatus, assignee: fresh.assignee })) {+ if (!isReportClaimable({ status: fresh.status as SignalReportStatus, assignee: fresh.assignee }, currentUserUuid)) {return { fresh, updated: null }}try {- const request = reportClaimRequest(fresh, true)+ const request = reportClaimRequest(fresh, true, { currentUserUuid })return {fresh,updated: await withInboxWriteTimeout('claim', (options) =>@@ -79,25 +111,31 @@ export type ReportClaimOutcome =export async function requestReportClaim(teamId: string,report: Pick<SignalReport, 'id' | 'assignee'>,- claimed: boolean+ claimed: boolean,+ options: ReportClaimOptions): Promise<ReportClaimOutcome> {try {- const request = reportClaimRequest(report, claimed)+ const request = reportClaimRequest(report, claimed, options)return {ok: true,- updated: await withInboxWriteTimeout('claim', (options) =>- signalsReportsClaim(teamId, report.id, request, options)+ updated: await withInboxWriteTimeout('claim', (requestOptions) =>+ signalsReportsClaim(teamId, report.id, request, requestOptions)),}} catch (error) {const conflict = error instanceof ApiError && error.status === 409- const retry = conflict && claimed ? await claimFromFreshReport(teamId, report.id) : null+ // A confirmed takeover does not retry: the claim may now belong to a person the user did not confirm.+ const retry =+ conflict && claimed && !options.takeover+ ? await claimFromFreshReport(teamId, report.id, options.currentUserUuid)+ : nullif (retry?.updated) {return { ok: true, updated: retry.updated }}const message = !conflict? "Couldn't update who's working on this report. Try again."- : !retry || (retry.fresh && reportClaimant(retry.fresh))+ : !options.takeover &&+ (!retry || (retry.fresh && teammateClaimHolder(retry.fresh, options.currentUserUuid)))? 'Someone else is already working on this report.': 'This report changed. Check it and try again.'return { ok: false, conflict, message }diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yamlindex f8ab7c2797e6..412991137e47 100644--- a/products/signals/mcp/tools.yaml+++ b/products/signals/mcp/tools.yaml@@ -410,11 +410,14 @@ tools:title: Update work on an inbox reportdescription: >Start, resume, or release work on an inbox report. Returns `assignee.claim_id` for the work attempt; pass it- on later updates. For internal task agents, claiming records the task association automatically. Add- pull_requests (GitHub PR URLs) in the same call, including when you start work. A report resolves when every- linked PR is closed or merged and at least one merged, and it is suppressed when all closed without merging.- Open, draft, unknown, or no PRs do not complete it. Repositories without a connected GitHub integration keep- unknown PR state, so resolve those reports with inbox-reports-set-state.+ on later updates. For internal task agents, claiming records the task association automatically. Another+ actor's active claim requires explicit takeover=true. When another person holds the claim, directly or+ through their agent, do not take it over on your own: tell your user who holds it and since when, and ask+ first. That takeover also needs takeover_claim_id, and the person is notified. Add pull_requests (GitHub PR+ URLs) in the same call, including when you start work. A report resolves when every linked PR is closed or+ merged and at least one merged, and it is suppressed when all closed without merging. Open, draft, unknown,+ or no PRs do not complete it. Repositories without a connected GitHub integration keep unknown PR state, so+ resolve those reports with inbox-reports-set-state.param_overrides:id:aliases:@@ -560,8 +563,10 @@ tools:agent_note: >You may inspect reports without claiming them. A claim indicates active work that should not be duplicated.Before claiming a report, read the report and its work log. If you decide to begin working to fix the issues- identified in the report, call inbox-reports-claim to record that you are working on it. Taking ownership- from another actor requires `takeover=true`.+ identified in the report, call inbox-reports-claim to record that you are working on it, before you change+ any code. If the report's `assignee` shows that another person or their agent is working on it, tell your+ user and ask before you take it over. Taking ownership from another actor requires `takeover=true`, and from+ another person also `takeover_claim_id`.If you create a pull request implementing the remediation, call inbox-reports-claim with the returned`claim_id` and `pull_requests` to add it. Send all currently known PRs together, including stacks and@@ -650,8 +655,10 @@ tools:agent_note: >You may inspect reports without claiming them. A claim indicates active work that should not be duplicated.Before claiming a report, read the report and its work log. If you decide to begin working to fix the issues- identified in the report, call inbox-reports-claim to record that you are working on it. Taking ownership- from another actor requires `takeover=true`.+ identified in the report, call inbox-reports-claim to record that you are working on it, before you change+ any code. If the report's `assignee` shows that another person or their agent is working on it, tell your+ user and ask before you take it over. Taking ownership from another actor requires `takeover=true`, and from+ another person also `takeover_claim_id`.Before work, read the work log and follow the newest applicable `## Verification plan`. Confirm the currentstate before work and the outcome after the chosen resolution.diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex d7d3e8199df2..eeecb631d6d6 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -8042,7 +8042,7 @@}},"inbox-reports-claim": {- "description": "Start, resume, or release work on an inbox report. Returns `assignee.claim_id` for the work attempt; pass it on later updates. For internal task agents, claiming records the task association automatically. Add pull_requests (GitHub PR URLs) in the same call, including when you start work. A report resolves when every linked PR is closed or merged and at least one merged, and it is suppressed when all closed without merging. Open, draft, unknown, or no PRs do not complete it. Repositories without a connected GitHub integration keep unknown PR state, so resolve those reports with inbox-reports-set-state.",+ "description": "Start, resume, or release work on an inbox report. Returns `assignee.claim_id` for the work attempt; pass it on later updates. For internal task agents, claiming records the task association automatically. Another actor's active claim requires explicit takeover=true. When another person holds the claim, directly or through their agent, do not take it over on your own: tell your user who holds it and since when, and ask first. That takeover also needs takeover_claim_id, and the person is notified. Add pull_requests (GitHub PR URLs) in the same call, including when you start work. A report resolves when every linked PR is closed or merged and at least one merged, and it is suppressed when all closed without merging. Open, draft, unknown, or no PRs do not complete it. Repositories without a connected GitHub integration keep unknown PR state, so resolve those reports with inbox-reports-set-state.","category": "Signals","feature": "signals","summary": "Update work on an inbox report",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex bcb1e2e2dbe2..c71f39768ff1 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -8274,7 +8274,7 @@}},"inbox-reports-claim": {- "description": "Start, resume, or release work on an inbox report. Returns `assignee.claim_id` for the work attempt; pass it on later updates. For internal task agents, claiming records the task association automatically. Add pull_requests (GitHub PR URLs) in the same call, including when you start work. A report resolves when every linked PR is closed or merged and at least one merged, and it is suppressed when all closed without merging. Open, draft, unknown, or no PRs do not complete it. Repositories without a connected GitHub integration keep unknown PR state, so resolve those reports with inbox-reports-set-state.",+ "description": "Start, resume, or release work on an inbox report. Returns `assignee.claim_id` for the work attempt; pass it on later updates. For internal task agents, claiming records the task association automatically. Another actor's active claim requires explicit takeover=true. When another person holds the claim, directly or through their agent, do not take it over on your own: tell your user who holds it and since when, and ask first. That takeover also needs takeover_claim_id, and the person is notified. Add pull_requests (GitHub PR URLs) in the same call, including when you start work. A report resolves when every linked PR is closed or merged and at least one merged, and it is suppressed when all closed without merging. Open, draft, unknown, or no PRs do not complete it. Repositories without a connected GitHub integration keep unknown PR state, so resolve those reports with inbox-reports-set-state.","category": "Signals","feature": "signals","summary": "Update work on an inbox report",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex ce5fbb1b8d69..6c2b98af0d80 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -106662,7 +106662,7 @@ export namespace Schemas {pull_requests?: string[];/** Explicitly end another actor's claim and take ownership. */takeover?: boolean;- /** With takeover, the claim the caller expects to replace. The takeover is rejected when a different claim is active, so a takeover based on a stale read cannot replace a newer claim. */+ /** With takeover, the claim the caller expects to replace. The takeover is rejected when a different claim is active, so a takeover based on a stale read cannot replace a newer claim. Required to take over a claim that another person holds, directly or through their agent. That person is notified. */takeover_claim_id?: string;/** Compatibility alias for adding one PR. Prefer pull_requests for new callers. */pr_url?: string;diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.tsindex 7719ff33ef62..86e426470e7b 100644--- a/services/mcp/src/generated/signals/api.ts+++ b/services/mcp/src/generated/signals/api.ts@@ -996,7 +996,7 @@ export const SignalsReportsClaimBody = () => zod.object({.string().optional().describe(- 'With takeover, the claim the caller expects to replace. The takeover is rejected when a different claim is active, so a takeover based on a stale read cannot replace a newer claim.'+ 'With takeover, the claim the caller expects to replace. The takeover is rejected when a different claim is active, so a takeover based on a stale read cannot replace a newer claim. Required to take over a claim that another person holds, directly or through their agent. That person is notified.'),pr_url: zod.url()diff --git a/services/mcp/src/tools/generated/signals.ts b/services/mcp/src/tools/generated/signals.tsindex dc9da0d83021..8230320420e0 100644--- a/services/mcp/src/tools/generated/signals.ts+++ b/services/mcp/src/tools/generated/signals.ts@@ -904,7 +904,7 @@ const inboxReportsList = (): ToolBase<},'/inbox'),- 'You may inspect reports without claiming them. A claim indicates active work that should not be duplicated. Before claiming a report, read the report and its work log. If you decide to begin working to fix the issues identified in the report, call inbox-reports-claim to record that you are working on it. Taking ownership from another actor requires `takeover=true`.\nIf you create a pull request implementing the remediation, call inbox-reports-claim with the returned `claim_id` and `pull_requests` to add it. Send all currently known PRs together, including stacks and cross-repository changes. Release the claim if you stop work without completing the report. If the report should be considered resolved without a pull request, or PostHog cannot observe the pull request merge, resolve it with inbox-reports-set-state.\n'+ "You may inspect reports without claiming them. A claim indicates active work that should not be duplicated. Before claiming a report, read the report and its work log. If you decide to begin working to fix the issues identified in the report, call inbox-reports-claim to record that you are working on it, before you change any code. If the report's `assignee` shows that another person or their agent is working on it, tell your user and ask before you take it over. Taking ownership from another actor requires `takeover=true`, and from another person also `takeover_claim_id`.\nIf you create a pull request implementing the remediation, call inbox-reports-claim with the returned `claim_id` and `pull_requests` to add it. Send all currently known PRs together, including stacks and cross-repository changes. Release the claim if you stop work without completing the report. If the report should be considered resolved without a pull request, or PostHog cannot observe the pull request merge, resolve it with inbox-reports-set-state.\n")},})@@ -964,7 +964,7 @@ const inboxReportsRetrieve = (): ToolBase<})return withAgentNote(await withPostHogUrl(context, result, `/inbox/${result.id}`),- 'You may inspect reports without claiming them. A claim indicates active work that should not be duplicated. Before claiming a report, read the report and its work log. If you decide to begin working to fix the issues identified in the report, call inbox-reports-claim to record that you are working on it. Taking ownership from another actor requires `takeover=true`.\nBefore work, read the work log and follow the newest applicable `## Verification plan`. Confirm the current state before work and the outcome after the chosen resolution.\nIf you create a pull request implementing the remediation, call inbox-reports-claim with the returned `claim_id` and `pull_requests` to add it. Send all currently known PRs together, including stacks and cross-repository changes. Release the claim if you stop work without completing the report. If the report should be considered resolved without a pull request, or PostHog cannot observe the pull request merge, resolve it with inbox-reports-set-state.\n'+ "You may inspect reports without claiming them. A claim indicates active work that should not be duplicated. Before claiming a report, read the report and its work log. If you decide to begin working to fix the issues identified in the report, call inbox-reports-claim to record that you are working on it, before you change any code. If the report's `assignee` shows that another person or their agent is working on it, tell your user and ask before you take it over. Taking ownership from another actor requires `takeover=true`, and from another person also `takeover_claim_id`.\nBefore work, read the work log and follow the newest applicable `## Verification plan`. Confirm the current state before work and the outcome after the chosen resolution.\nIf you create a pull request implementing the remediation, call inbox-reports-claim with the returned `claim_id` and `pull_requests` to add it. Send all currently known PRs together, including stacks and cross-repository changes. Release the claim if you stop work without completing the report. If the report should be considered resolved without a pull request, or PostHog cannot observe the pull request merge, resolve it with inbox-reports-set-state.\n")},})diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-reports-claim.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-reports-claim.jsonindex f888e322c302..46d35ca1c4b0 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-reports-claim.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-reports-claim.json@@ -35,7 +35,7 @@"type": "boolean"},"takeover_claim_id": {- "description": "With takeover, the claim the caller expects to replace. The takeover is rejected when a different claim is active, so a takeover based on a stale read cannot replace a newer claim.",+ "description": "With takeover, the claim the caller expects to replace. The takeover is rejected when a different claim is active, so a takeover based on a stale read cannot replace a newer claim. Required to take over a claim that another person holds, directly or through their agent. That person is notified.","type": "string"}},