: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): show priority and an implement button in inbox slack messages (#129737)
Dylan Martinc497a8097c73
diff --git a/products/signals/backend/report_urls.py b/products/signals/backend/report_urls.pyindex 1e7435dbaf84..48513c65c6e4 100644--- a/products/signals/backend/report_urls.py+++ b/products/signals/backend/report_urls.py@@ -3,6 +3,8 @@Each link carries a `link_source` query param. The inbox reads it, records it on`Inbox report opened`, and removes it from the address bar. The inbox filters already use `source`. The values must match`INBOX_REPORT_LINK_SOURCES` in `frontend/inbox/inboxAnalytics.ts`.++A link can also carry a `link_action` query param. The inbox reads it once and removes it too."""from enum import StrEnum@@ -25,9 +27,19 @@ class ReportLinkSource(StrEnum):TODAY = "today"-def report_path(team_id: int, report_id: str | UUID, source: ReportLinkSource) -> str:- return f"/project/{team_id}/inbox/reports/{report_id}?link_source={source.value}"+class ReportLinkAction(StrEnum):+ # Opens the implementation choices of the report's Implement button.+ IMPLEMENT = "implement"+++def report_path(+ team_id: int, report_id: str | UUID, source: ReportLinkSource, action: ReportLinkAction | None = None+) -> str:+ path = f"/project/{team_id}/inbox/reports/{report_id}?link_source={source.value}"+ return f"{path}&link_action={action.value}" if action else path-def build_report_url(team_id: int, report_id: str | UUID, source: ReportLinkSource) -> str:- return absolute_uri(report_path(team_id, report_id, source))+def build_report_url(+ team_id: int, report_id: str | UUID, source: ReportLinkSource, action: ReportLinkAction | None = None+) -> str:+ return absolute_uri(report_path(team_id, report_id, source, action))diff --git a/products/signals/backend/slack_inbox_notifications.py b/products/signals/backend/slack_inbox_notifications.pyindex b748e074a628..b6d44f6eb8a7 100644--- a/products/signals/backend/slack_inbox_notifications.py+++ b/products/signals/backend/slack_inbox_notifications.py@@ -37,6 +37,8 @@ from posthog.slack.formatting import (from posthog.slack.markdown import slack_markdown_block as _markdown_blockfrom products.signals.backend.assignment_flags import assignment_side_effects_allowed+from products.signals.backend.enums import ReportLinkKind+from products.signals.backend.implementation_pr import fetch_implementation_prs_for_reportsfrom products.signals.backend.models import (AutonomyPriority,SignalReport,@@ -54,7 +56,7 @@ from products.signals.backend.report_generation.resolve_reviewers import (resolve_org_github_login_to_users,resolve_org_users_by_uuid,)-from products.signals.backend.report_urls import ReportLinkSource, build_report_url+from products.signals.backend.report_urls import ReportLinkAction, ReportLinkSource, build_report_urlfrom products.signals.backend.scout_authorship import report_is_hidden_from_inboxfrom products.signals.backend.slack_formatting import (first_sentence as _first_sentence,@@ -65,7 +67,10 @@ from products.signals.backend.slack_formatting import ()from products.signals.backend.slack_notification_targets import is_slack_member_target, lookup_slack_user_id_by_emailfrom products.signals.backend.slack_report_threads import record_report_slack_thread+from products.signals.backend.task_run_artefacts import SIGNALS_PRODUCT, TASK_RUN_TYPE_IMPLEMENTATION+from products.signals.backend.typed_report_links import incoming_linksfrom products.slack_app.backend.facade.api import slack_followup_invite+from products.tasks.backend.facade import api as tasks_facade# Actionability values shown in the inbox Reports tab. Slack notifications mirror that tab, so a# report notifies iff its latest actionability judgment is one of these (and it's READY).@@ -92,6 +97,14 @@ _PRIORITY_ORDER: tuple[str, ...] = (AutonomyPriority.P3,AutonomyPriority.P4,)+# Keep in sync with PRIORITY_TAG_TYPE in frontend/inbox/filterOptions.tsx, so Slack and the inbox agree.+_PRIORITY_EMOJI: dict[str, str] = {+ AutonomyPriority.P0: "🔴",+ AutonomyPriority.P1: "🟠",+ AutonomyPriority.P2: "🟡",+ AutonomyPriority.P3: "🔵",+ AutonomyPriority.P4: "⚪️",+}# Report titles are PR-style ("fix(scope): Description"). The inbox shows only the description, so# Slack does too. Keep in sync with CONVENTIONAL_COMMIT_TITLE in frontend/inbox/utils/reportPresentation.ts.@@ -146,22 +159,55 @@ def _latest_priority(report: SignalReport) -> str | None:return value if isinstance(value, str) else None-def _latest_actionability(report: SignalReport) -> str | None:+def _latest_actionability_judgment(report: SignalReport) -> dict:art = (report.artefacts.filter(type=SignalReportArtefact.ArtefactType.ACTIONABILITY_JUDGMENT).order_by("-created_at").first())if art is None:- return None+ return {}try:data = json.loads(art.content)except (json.JSONDecodeError, TypeError, ValueError):- return None- if not isinstance(data, dict):- return None- value = data.get("actionability")- return value if isinstance(value, str) else None+ return {}+ return data if isinstance(data, dict) else {}+++def _offers_implementation(judgment: dict) -> bool:+ """Whether the message offers Implement: the research says the fix is ready and nobody has started it."""+ return (+ judgment.get("actionability") == ActionabilityChoice.IMMEDIATELY_ACTIONABLE.value+ and judgment.get("already_addressed") is not True+ )+++def _implementation_underway(report: SignalReport) -> bool:+ """Whether the report has a pull request or an implementation run that has not ended.++ The inbox then shows View task instead of the Implement choices, so the message must not offer+ Implement. Auto-start often opens the pull request before the notification goes out.+ """+ report_id = str(report.id)+ if fetch_implementation_prs_for_reports([report_id], team_id=report.team_id, using="default").get(report_id):+ return True+ task_ids = [+ run.task_id+ for run in SignalReport.associated_task_runs(+ report_id=report_id, team_id=report.team_id, product=SIGNALS_PRODUCT, type=TASK_RUN_TYPE_IMPLEMENTATION+ )+ ]+ return any(not run.is_terminal for run in tasks_facade.get_latest_run_by_task(task_ids).values())+++def _should_offer_implementation(report: SignalReport, judgment: dict) -> bool:+ """Whether the message offers Implement, matching when the inbox offers its Implement choices."""+ if not _offers_implementation(judgment):+ return False+ # A plan parent has no run of its own: the reports that are part of it do the work.+ if incoming_links(team_id=report.team_id, report_id=report.id, kinds=(ReportLinkKind.PART_OF,)):+ return False+ return not _implementation_underway(report)def resolve_org_suggested_reviewer_user_ids(*, team_id: int, report_ids: Collection[str]) -> dict[str, set[int]]:@@ -355,7 +401,12 @@ def _section_body(markdown: str) -> str:def _build_message_blocks(- report: SignalReport, *, reviewer_mentions: list[str], use_section_blocks: bool = False+ report: SignalReport,+ *,+ reviewer_mentions: list[str],+ use_section_blocks: bool = False,+ priority: str | None = None,+ offer_implementation: bool = False,) -> tuple[list[dict], str]:title_line = _display_title(report.title)header_text = (@@ -390,23 +441,34 @@ def _build_message_blocks(body_block,]+ context_parts: list[str] = []+ if priority_emoji := _PRIORITY_EMOJI.get(priority or ""):+ context_parts.append(f"{priority_emoji} *{priority}*")# Plain-text blocks would show the raw mention token instead of resolving the user.if reviewer_mentions:owner_label = "Suggested owner" if len(reviewer_mentions) == 1 else "Suggested owners"- blocks.append(+ context_parts.append(f"👤 {owner_label}: {' '.join(reviewer_mentions)}")+ if context_parts:+ blocks.append({"type": "context", "elements": [{"type": "mrkdwn", "text": " · ".join(context_parts)}]})++ action_elements: list[dict] = []+ # A link, not an interactive button: the inbox runs its own access, quota and repository checks.+ if offer_implementation:+ action_elements.append({- "type": "context",- "elements": [{"type": "mrkdwn", "text": f"👤 {owner_label}: {' '.join(reviewer_mentions)}"}],+ "type": "button",+ "text": {"type": "plain_text", "text": "Implement", "emoji": True},+ "style": "primary",+ "url": build_report_url(report.team_id, report.id, ReportLinkSource.SLACK, ReportLinkAction.IMPLEMENT),})-- action_elements: list[dict] = [+ action_elements.append({"type": "button","text": {"type": "plain_text", "text": "Review in PostHog", "emoji": True},"url": build_report_url(report.team_id, report.id, ReportLinkSource.SLACK),}- ]+ )blocks.append({"type": "actions", "elements": action_elements})return blocks, _escape_mrkdwn(title_line)@@ -534,6 +596,8 @@ def _deliver_route_notification(route: _ChannelRoute,*,trigger: str,+ priority: str | None,+ offer_implementation: bool,) -> bool:"""Post one report notification to a route's destination.@@ -562,6 +626,8 @@ def _deliver_route_notification(report,reviewer_mentions=mentions,use_section_blocks=organization_inbox_slack_section_blocks_enabled(report.team.organization_id),+ priority=priority,+ offer_implementation=offer_implementation,)# Added here rather than inside the block builder, which stays free of the integration so it# can be tested without one. Approval is read now, not assumed from generation time: a@@ -598,11 +664,15 @@ def _deliver_to_routes(routes: list[_ChannelRoute],*,trigger: str,+ priority: str | None,+ offer_implementation: bool,) -> int:"""Post the report to every route, returning how many top-level messages were sent."""sent = 0for route in routes:- if _deliver_route_notification(report, route, trigger=trigger):+ if _deliver_route_notification(+ report, route, trigger=trigger, priority=priority, offer_implementation=offer_implementation+ ):sent += 1return sent@@ -669,7 +739,8 @@ def dispatch_inbox_item_notifications(report_id: str, team_id: int) -> int:# Mirror the inbox Reports tab: notify only for actionable reports (READY is enforced upstream# in the notification activity). Priority is read below for min-priority routing, but# it's optional now — an actionable report notifies even without a priority.- if _latest_actionability(report) not in _ACTIONABLE_VALUES:+ actionability = _latest_actionability_judgment(report)+ if actionability.get("actionability") not in _ACTIONABLE_VALUES:logger.info("dispatch_inbox_item_notifications: report not actionable, skipping",extra={"report_id": report_id, "team_id": team_id},@@ -702,7 +773,13 @@ def dispatch_inbox_item_notifications(report_id: str, team_id: int) -> int:)return 0- sent = _deliver_to_routes(report, routes, trigger="report_ready")+ sent = _deliver_to_routes(+ report,+ routes,+ trigger="report_ready",+ priority=priority,+ offer_implementation=_should_offer_implementation(report, actionability),+ )logger.info("dispatch_inbox_item_notifications: complete",extra={"report_id": report_id, "team_id": team_id, "messages_sent": sent, "routes": len(routes)},@@ -800,7 +877,8 @@ def dispatch_reviewer_added_notifications(# Mirror the initial notification's gate: only reports actually surfaced in the inbox# (READY and actionable) notify. Status is checked here because — unlike the generation# pipeline — this path has no upstream READY guarantee.- if report.status != SignalReport.Status.READY or _latest_actionability(report) not in _ACTIONABLE_VALUES:+ actionability = _latest_actionability_judgment(report)+ if report.status != SignalReport.Status.READY or actionability.get("actionability") not in _ACTIONABLE_VALUES:return 0user_ids = _resolve_added_reviewer_user_ids(@@ -814,7 +892,13 @@ def dispatch_reviewer_added_notifications(if not routes:return 0- sent = _deliver_to_routes(report, routes, trigger="reviewer_added")+ sent = _deliver_to_routes(+ report,+ routes,+ trigger="reviewer_added",+ priority=priority,+ offer_implementation=_should_offer_implementation(report, actionability),+ )logger.info("dispatch_reviewer_added_notifications: complete",extra={"report_id": report_id, "team_id": team_id, "messages_sent": sent, "routes": len(routes)},diff --git a/products/signals/backend/test/test_slack_inbox_notifications.py b/products/signals/backend/test/test_slack_inbox_notifications.pyindex cf2e97f5e94c..c76713a62994 100644--- a/products/signals/backend/test/test_slack_inbox_notifications.py+++ b/products/signals/backend/test/test_slack_inbox_notifications.py@@ -17,11 +17,15 @@ from posthog.models.integration import Integrationfrom posthog.models.organization import OrganizationMembershipfrom products.access_control.backend.models.access_control import AccessControl+from products.signals.backend.artefact_schemas import ReportLink+from products.signals.backend.enums import ReportLinkKindfrom products.signals.backend.facade.api import set_default_slack_notification_channelfrom products.signals.backend.models import (+ ArtefactAttribution,AutonomyPriority,SignalReport,SignalReportArtefact,+ SignalReportTask,SignalScoutConfig,SignalScoutRun,SignalUserAutonomyConfig,@@ -30,6 +34,7 @@ from products.signals.backend.report_generation.research import ActionabilityChofrom products.signals.backend.slack_inbox_notifications import (_build_message_blocks,_meets_min_priority,+ _offers_implementation,_resolve_reviewer_mentions,_summary_excerpt,dispatch_inbox_item_notifications,@@ -65,6 +70,20 @@ def test_meets_min_priority(report_priority: str | None, min_priority: str | Nonassert _meets_min_priority(report_priority, min_priority) is expected+ ("judgment", "expected"),+ [+ ({"actionability": ActionabilityChoice.IMMEDIATELY_ACTIONABLE.value}, True),+ ({"actionability": ActionabilityChoice.IMMEDIATELY_ACTIONABLE.value, "already_addressed": False}, True),+ ({"actionability": ActionabilityChoice.IMMEDIATELY_ACTIONABLE.value, "already_addressed": True}, False),+ ({"actionability": ActionabilityChoice.REQUIRES_HUMAN_INPUT.value}, False),+ ({}, False),+ ],+)+def test_offers_implementation_only_for_unstarted_ready_fixes(judgment: dict, expected: bool) -> None:+ assert _offers_implementation(judgment) is expected++@pytest.mark.parametrize(("summary", "expected"),[@@ -120,7 +139,13 @@ def test_build_message_blocks_includes_recipient_and_open_in_posthog_button(use_),signal_count=12,)- blocks, text = _build_message_blocks(report, reviewer_mentions=["<@U123>"], use_section_blocks=use_section_blocks)+ blocks, text = _build_message_blocks(+ report,+ reviewer_mentions=["<@U123>"],+ use_section_blocks=use_section_blocks,+ priority=AutonomyPriority.P1,+ offer_implementation=True,+ )assert blocks[0]["text"]["text"] == "Checkout errors spiked"if use_section_blocks:@@ -141,11 +166,12 @@ def test_build_message_blocks_includes_recipient_and_open_in_posthog_button(use_}# A mention in plain_text would render as the raw token, never pinging anyone.assert all("<@" not in t for t in _plain_text_block_texts(blocks))- assert blocks[2]["elements"][0]["text"] == "👤 Suggested owner: <@U123>"- buttons = blocks[3]["elements"]- assert len(buttons) == 1- assert buttons[0]["text"]["text"] == "Review in PostHog"- assert buttons[0]["url"] == f"{settings.SITE_URL}/project/42/inbox/reports/report-uuid?link_source=slack"+ assert blocks[2]["elements"][0]["text"] == "🟠 *P1* · 👤 Suggested owner: <@U123>"+ report_url = f"{settings.SITE_URL}/project/42/inbox/reports/report-uuid?link_source=slack"+ assert [(button["text"]["text"], button.get("style"), button["url"]) for button in blocks[3]["elements"]] == [+ ("Implement", "primary", f"{report_url}&link_action=implement"),+ ("Review in PostHog", None, report_url),+ ]assert text == "Checkout errors spiked"@@ -420,14 +446,14 @@ def test_dispatch_sends_to_configured_reviewer(assert blocks[0]["text"]["text"] == "Test report"context_texts = [block["elements"][0]["text"] for block in blocks if block["type"] == "context"]if expects_mention:- assert "👤 Suggested owner: <@U_REVIEWER>" in context_texts+ assert "🟠 *P1* · 👤 Suggested owner: <@U_REVIEWER>" in context_textselse:+ assert "🟠 *P1*" in context_textsassert not any("Suggested owner" in text for text in context_texts)assert all("<@" not in t for t in _plain_text_block_texts(blocks))actions = next(block for block in blocks if block["type"] == "actions")- assert actions["elements"][0]["url"] == (- f"{settings.SITE_URL}/project/{team.id}/inbox/reports/{report.id}?link_source=slack"- )+ report_url = f"{settings.SITE_URL}/project/{team.id}/inbox/reports/{report.id}?link_source=slack"+ assert [element["url"] for element in actions["elements"]] == [f"{report_url}&link_action=implement", report_url]@pytest.mark.django_db@@ -687,6 +713,86 @@ def test_dispatch_skips_non_actionable_report(org_and_team):assert fake_client.chat_postMessage.call_count == 0+ ("run_status", "pr_url", "expects_implement"),+ [+ (None, None, True),+ ("in_progress", None, False),+ ("completed", "https://github.com/example/repo/pull/1", False),+ # The inbox offers Implement again after a run that ended without a pull request.+ ("failed", None, True),+ ],+)+def test_dispatch_offers_implement_only_without_implementation_underway(+ org_and_team, run_status, pr_url, expects_implement+):+ org, team = org_and_team+ reviewer = _make_reviewer_user(org, "[email protected]", "impl-bot")+ _make_slack_integration(team, reviewer)+ _set_team_channel(team, "CTEAM|#posthog-signals")+ report = _make_ready_report(team, priority=AutonomyPriority.P1)+ if run_status:+ Task = apps.get_model("tasks", "Task")+ TaskRun = apps.get_model("tasks", "TaskRun")+ task = Task.objects.create(+ team=team, title="impl", description="d", origin_product=Task.OriginProduct.SIGNAL_REPORT+ )+ SignalReportTask.objects.create(team=team, report=report, task=task, relationship="implementation")+ TaskRun.objects.create(team=team, task=task, status=run_status, output={"pr_url": pr_url})++ fake_client = MagicMock()+ with patch("products.signals.backend.slack_inbox_notifications.SlackIntegration") as slack_cls:+ slack_cls.return_value.client = fake_client+ sent = dispatch_inbox_item_notifications(str(report.id), team.id)++ assert sent == 1+ assert _implement_offered(fake_client.chat_postMessage) is expects_implement+++def _implement_offered(post_message: MagicMock) -> bool:+ blocks = post_message.call_args.kwargs["blocks"]+ return any(+ element["text"]["text"] == "Implement"+ for block in blocks+ if block["type"] == "actions"+ for element in block["elements"]+ )++[email protected]("trigger", ["report_ready", "reviewer_added"])+def test_dispatch_does_not_offer_implement_for_a_plan_parent(org_and_team, trigger):+ org, team = org_and_team+ reviewer = _make_reviewer_user(org, "[email protected]", "plan-bot")+ integration = _make_slack_integration(team, reviewer)+ SignalUserAutonomyConfig.objects.create(+ user=reviewer, slack_notification_integration=integration, slack_notification_channel="COWN|#mine"+ )+ parent = _make_ready_report(team, priority=AutonomyPriority.P1, suggested_logins=["plan-bot"])+ step = _make_ready_report(team, title="Step")+ SignalReportArtefact.add_log(+ team_id=team.id,+ report_id=str(step.id),+ content=ReportLink(kind=ReportLinkKind.PART_OF, report_id=str(parent.id)),+ attribution=ArtefactAttribution.system(),+ )++ fake_client = MagicMock()+ with (+ patch("products.signals.backend.slack_inbox_notifications.SlackIntegration") as slack_cls,+ patch("products.signals.backend.slack_inbox_notifications.lookup_slack_user_id_by_email", return_value=None),+ ):+ slack_cls.return_value.client = fake_client+ if trigger == "report_ready":+ sent = dispatch_inbox_item_notifications(str(parent.id), team.id)+ else:+ sent = dispatch_reviewer_added_notifications(str(parent.id), team.id, ["plan-bot"])++ assert sent == 1+ assert not _implement_offered(fake_client.chat_postMessage)++@pytest.mark.django_dbdef test_dispatch_notifies_requires_human_input_report_without_priority(org_and_team):org, team = org_and_teamdiff --git a/products/signals/frontend/inbox/components/detail/ImplementButton.test.tsx b/products/signals/frontend/inbox/components/detail/ImplementButton.test.tsxindex 3c4f098b5387..7b6ee7f072eb 100644--- a/products/signals/frontend/inbox/components/detail/ImplementButton.test.tsx+++ b/products/signals/frontend/inbox/components/detail/ImplementButton.test.tsx@@ -81,7 +81,34 @@ describe('ImplementButton', () => {await user.click(screen.getByTestId('inbox-report-create-pr-submit'))expect(createPrFromReport).toHaveBeenCalledWith(expect.objectContaining({ id: 'report-1' }), undefined)- expect(jest.mocked(captureInboxReportAction).mock.calls[0][0].extra).toEqual({ has_feedback: false })+ expect(jest.mocked(captureInboxReportAction).mock.calls[0][0].extra).toEqual({+ has_feedback: false,+ opened_from_link: false,+ })+ })++ it('opens the implementation choices when a link asks for them', async () => {+ const user = userEvent.setup()+ const onChoicesOpenedFromLink = jest.fn()+ render(+ <ImplementButton+ report={makeReport()}+ openChoicesFromLink+ onChoicesOpenedFromLink={onChoicesOpenedFromLink}+ />+ )++ await waitFor(() => expect(screen.getByText('Implement with PostHog')).toBeInTheDocument())+ expect(onChoicesOpenedFromLink).toHaveBeenCalled()+ expect(createPrFromReport).not.toHaveBeenCalled()++ await user.click(screen.getByTestId('inbox-report-create-pr-submit'))++ expect(createPrFromReport).toHaveBeenCalledWith(expect.objectContaining({ id: 'report-1' }), undefined)+ expect(jest.mocked(captureInboxReportAction).mock.calls[0][0].extra).toEqual({+ has_feedback: false,+ opened_from_link: true,+ })})it.each([TaskRunStatus.QUEUED, TaskRunStatus.IN_PROGRESS])(@@ -179,7 +206,10 @@ describe('ImplementButton', () => {expect.objectContaining({ id: 'report-1' }),'Keep the existing API')- expect(jest.mocked(captureInboxReportAction).mock.calls[0][0].extra).toEqual({ has_feedback: true })+ expect(jest.mocked(captureInboxReportAction).mock.calls[0][0].extra).toEqual({+ has_feedback: true,+ opened_from_link: false,+ })})it('copies a prompt that claims the report and attaches the finished pull request', async () => {diff --git a/products/signals/frontend/inbox/components/detail/ImplementButton.tsx b/products/signals/frontend/inbox/components/detail/ImplementButton.tsxindex e9cf15fb208e..c978142db3e7 100644--- a/products/signals/frontend/inbox/components/detail/ImplementButton.tsx+++ b/products/signals/frontend/inbox/components/detail/ImplementButton.tsx@@ -1,5 +1,5 @@import { useActions, useValues } from 'kea'-import { useState } from 'react'+import { useEffect, useRef, useState } from 'react'import { IconCopy, IconPullRequest } from '@posthog/icons'import { LemonButton, LemonMenuOverlay, lemonToast } from '@posthog/lemon-ui'@@ -24,6 +24,8 @@ interface ImplementButtonProps {surface?: 'detail_pane' | 'triage_mode'implementationDisabledReason?: string | nullreportTaskToOpen?: ReportTaskEntry | null+ openChoicesFromLink?: boolean+ onChoicesOpenedFromLink?: () => void}export function ImplementButton({@@ -31,6 +33,8 @@ export function ImplementButton({surface = 'detail_pane',implementationDisabledReason,reportTaskToOpen,+ openChoicesFromLink = false,+ onChoicesOpenedFromLink,}: ImplementButtonProps): JSX.Element {const { isCreatingPr, isDiscussing, createPrDisabledReason } = useValues(inboxTaskKickoffLogic)const {@@ -44,6 +48,14 @@ export function ImplementButton({const { createPrFromReport, openReportTask } = useActions(inboxTaskKickoffLogic)const [instructions, setInstructions] = useState('')const [choicesOpen, setChoicesOpen] = useState(false)+ const choicesOpenedFromLink = useRef(false)+ useEffect(() => {+ if (openChoicesFromLink) {+ choicesOpenedFromLink.current = true+ setChoicesOpen(true)+ onChoicesOpenedFromLink?.()+ }+ }, [openChoicesFromLink, onChoicesOpenedFromLink])const reportUrl = `${window.location.origin}${addProjectIdIfMissing(urls.inboxReport('reports', report.id))}`const disabledReason =@@ -74,7 +86,7 @@ export function ImplementButton({report,actionType: 'create_pr',surface,- extra: { has_feedback: trimmed.length > 0 },+ extra: { has_feedback: trimmed.length > 0, opened_from_link: choicesOpenedFromLink.current },})createPrFromReport(report, trimmed || undefined)}@@ -128,7 +140,12 @@ export function ImplementButton({'data-attr': 'inbox-report-create-pr-steer',dropdown: {visible: choicesOpen && !connectionOpen,- onVisibilityChange: setChoicesOpen,+ onVisibilityChange: (visible) => {+ if (!visible) {+ choicesOpenedFromLink.current = false+ }+ setChoicesOpen(visible)+ },placement: 'bottom-end',closeOnClickInside: false,overlay: (diff --git a/products/signals/frontend/inbox/components/detail/ReportDetail.tsx b/products/signals/frontend/inbox/components/detail/ReportDetail.tsxindex cf3171595228..f1bc3ac21c7f 100644--- a/products/signals/frontend/inbox/components/detail/ReportDetail.tsx+++ b/products/signals/frontend/inbox/components/detail/ReportDetail.tsx@@ -25,6 +25,7 @@ import { urls } from 'scenes/urls'import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'import { captureInboxReportAction } from '../../inboxAnalytics'+import { inboxSceneLogic } from '../../inboxSceneLogic'import { inboxDetailLayoutLogic } from '../../logics/inboxDetailLayoutLogic'import { inboxReportDetailLogic } from '../../logics/inboxReportDetailLogic'import { SignalCard } from '../../SignalCard'@@ -260,6 +261,8 @@ export function InboxDetailFrame({)const { evidenceRailCollapsed } = useValues(inboxDetailLayoutLogic)const { toggleEvidenceRail } = useActions(inboxDetailLayoutLogic)+ const { linkImplementReportId } = useValues(inboxSceneLogic)+ const { setLinkImplementReportId } = useActions(inboxSceneLogic)// The API returns evidence oldest-first, but a reader wants the most recent signal at the top of// the rail rather than after a scroll.const signals = [...(reportSignals ?? [])].sort(@@ -293,6 +296,8 @@ export function InboxDetailFrame({report={report}reportTaskToOpen={reportTaskToOpen}implementationDisabledReason={implementationDisabledReason}+ openChoicesFromLink={linkImplementReportId === report.id}+ onChoicesOpenedFromLink={() => setLinkImplementReportId(null)}/>) : nullconst summaryHasSolution = parseReportSummary(report.summary).sections.some(diff --git a/products/signals/frontend/inbox/inboxSceneLogic.test.ts b/products/signals/frontend/inbox/inboxSceneLogic.test.tsindex c888fc89b6ae..3777a38d6f8b 100644--- a/products/signals/frontend/inbox/inboxSceneLogic.test.ts+++ b/products/signals/frontend/inbox/inboxSceneLogic.test.ts@@ -369,7 +369,7 @@ describe('inboxSceneLogic routing', () => {})// A link PostHog wrote names its surface in `link_source`. The product filter keeps `source`. A tab that already saw the list can still- // open one, and the param leaves the address bar so a copied URL does not pass it on.+ // open one, and the param leaves the address bar so a copied URL does not pass it on. `link_action` leaves it the same way.it.each([{ name: 'no param', source: undefined, visitedList: false, method: 'deeplink', linkSource: null },{ name: 'a known source', source: 'slack', visitedList: false, method: 'deeplink', linkSource: 'slack' },@@ -389,17 +389,26 @@ describe('inboxSceneLogic routing', () => {},{ name: 'a source after the list', source: 'mcp', visitedList: true, method: 'deeplink', linkSource: 'mcp' },{ name: 'no param after the list', source: undefined, visitedList: true, method: 'click', linkSource: null },+ {+ name: 'the implement action',+ source: 'slack',+ linkAction: 'implement',+ visitedList: false,+ method: 'deeplink',+ linkSource: 'slack',+ },])('a report link with $name opens as $method with link source $linkSource',- async ({ source, visitedList, method, linkSource }) => {+ async ({ source, linkAction, visitedList, method, linkSource }) => {mountLogic()if (visitedList) {router.actions.push(urls.inbox('reports'))}- const url = combineUrl(- urls.inboxReport('reports', 'r1'),- source ? { link_source: source, source: 'github' } : { source: 'github' }- ).url+ const url = combineUrl(urls.inboxReport('reports', 'r1'), {+ source: 'github',+ ...(source ? { link_source: source } : {}),+ ...(linkAction ? { link_action: linkAction } : {}),+ }).urllet payload: { openMethod?: string; linkSource?: string | null } = {}await expectLogic(logic, () => router.actions.push(url)).toDispatchActions([@@ -413,6 +422,7 @@ describe('inboxSceneLogic routing', () => {])expect(payload).toMatchObject({ openMethod: method, linkSource })expect(router.values.searchParams).toEqual({ source: 'github' })+ expect(logic.values.linkImplementReportId).toBe(linkAction ? 'r1' : null)})diff --git a/products/signals/frontend/inbox/inboxSceneLogic.ts b/products/signals/frontend/inbox/inboxSceneLogic.tsindex dc931d3ba63b..c7abf0d00941 100644--- a/products/signals/frontend/inbox/inboxSceneLogic.ts+++ b/products/signals/frontend/inbox/inboxSceneLogic.ts@@ -232,12 +232,12 @@ function hasVisitedInboxList(): boolean {}// Not `source`: the inbox filters own that param for the product filter.-function hasLinkSource(searchParams: Record<string, any>): boolean {- return searchParams.link_source !== undefined+function hasLinkParams(searchParams: Record<string, any>): boolean {+ return searchParams.link_source !== undefined || searchParams.link_action !== undefined}-function withoutLinkSource(searchParams: Record<string, any>): Record<string, any> {- const { link_source: _linkSource, ...rest } = searchParams+function withoutLinkParams(searchParams: Record<string, any>): Record<string, any> {+ const { link_source: _linkSource, link_action: _linkAction, ...rest } = searchParamsreturn rest}@@ -483,6 +483,7 @@ export interface inboxSceneLogicValues {isScratchpadOpen: booleanisStaff: booleanisTriageOpen: boolean+ linkImplementReportId: string | nullscoutDetailTab: ScoutDetailTab | nullscoutTemplateDraft: ScoutCreateInitialValues | nullselectedReport: SignalReport | null@@ -555,6 +556,9 @@ export interface inboxSceneLogicActions {setFindingsOpen: (open: boolean) => {open: boolean}+ setLinkImplementReportId: (id: string | null) => {+ id: string | null+ }setRunsOpen: (open: boolean) => {open: boolean}@@ -639,6 +643,9 @@ export const inboxSceneLogic = kea<inboxSceneLogicType>([openMethod,linkSource,}),+ // A link with `link_action=implement`, such as the Implement button in Slack, asks the+ // report detail to open its implementation choices. The detail clears it once it opens them.+ setLinkImplementReportId: (id: string | null) => ({ id }),// Seed (or clear) the selected report synchronously from an already-loaded list row, so the// detail renders without a spinner while the authoritative fetch runs in the background.seedSelectedReport: (report: SignalReport | null) => ({ report }),@@ -767,6 +774,13 @@ export const inboxSceneLogic = kea<inboxSceneLogicType>([setSelectedReportId: (_, { id }) => id,},],+ linkImplementReportId: [+ null as string | null,+ {+ setLinkImplementReportId: (_, { id }) => id,+ setSelectedReportId: (state, { id }) => (state === id ? state : null),+ },+ ],// Null until a route sets a tab; `activeTab` fills in the landing tab.activeTabState: [null as InboxTabKey | null,@@ -1200,10 +1214,10 @@ export const inboxSceneLogic = kea<inboxSceneLogicType>([// queue, which the triage URL carries at this moment.openMethod === 'triage'? { back: removeProjectIdIfPresent(router.values.location.pathname) + router.values.location.search }- : withoutLinkSource(router.values.searchParams),+ : withoutLinkParams(router.values.searchParams),router.values.hashParams,// Replace, so Back does not return to the link URL and its `link_source`.- { replace: hasLinkSource(router.values.searchParams) },+ { replace: hasLinkParams(router.values.searchParams) },],setSelectedScoutSkillName: ({ findingId }) => [inboxSurfaceUrl(values),@@ -1397,9 +1411,12 @@ export const inboxSceneLogic = kea<inboxSceneLogicType>([fromTriage ? 'triage' : linkSource !== null || !hasVisitedInboxList() ? 'deeplink' : 'click',linkSource)- } else if (hasLinkSource(searchParams)) {+ } else if (hasLinkParams(searchParams)) {// A copied address bar must not pass the original `link_source` on to the next reader.- router.actions.replace(router.values.location.pathname, withoutLinkSource(searchParams), hashParams)+ router.actions.replace(router.values.location.pathname, withoutLinkParams(searchParams), hashParams)+ }+ if (searchParams.link_action === 'implement') {+ actions.setLinkImplementReportId(reportId)}},}