Skip to content

: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.

feat(signals): record where inbox report deep-link opens came from (#115069)

posthog[bot]31f0bd43a9fd
diff --git a/products/signals/backend/auto_start.py b/products/signals/backend/auto_start.py
index 1b7303556f9e..5b2f497db3a4 100644
--- a/products/signals/backend/auto_start.py
+++ b/products/signals/backend/auto_start.py
@@ -6,7 +6,6 @@ from datetime import datetime
from typing import Literal, TypedDict
from uuid import UUID
-from django.conf import settings
from django.db import transaction
from django.utils import timezone
from django.utils.text import slugify
@@ -59,6 +58,7 @@ from products.signals.backend.report_generation.resolve_reviewers import (
)
from products.signals.backend.report_generation.select_repo import RepoSelectionResult
from products.signals.backend.report_steering import NO_STEERING, ReportSteering, load_report_steering
+from products.signals.backend.report_urls import ReportLinkSource, build_report_url
from products.signals.backend.scout_authorship import report_is_from_background_scout, resolve_touching_scout_skills
from products.signals.backend.scout_harness.skill_loader import resolve_skill_owner_user_uuids
from products.signals.backend.signal_metadata import (
@@ -355,7 +355,7 @@ def _build_autostart_task_description(
supersede: SupersedeDecision = NO_SUPERSEDE,
) -> str:
priority_line = f"Priority: {priority.priority.value}\nReason: {priority.explanation}\n\n" if priority else ""
- report_link = f"{settings.SITE_URL}/project/{team_id}/inbox/reports/{report_id}"
+ report_link = build_report_url(team_id, report_id, ReportLinkSource.TASK)
source_links = ", ".join(f"[{ref.label}]({ref.url})" for ref in source_references or [])
source_issues_line = f"Source issues: {source_links}\n\n" if source_links else ""
source_reference_instruction = (
@@ -1068,7 +1068,7 @@ def start_requested_implementation(request: RequestedImplementation) -> str:
"pending_user_message": (
"The report has fresh research. Read its latest research artefacts, then reassess the existing "
"implementation. Update the existing pull request when appropriate.\n\n"
- f"Report: {settings.SITE_URL}/project/{request.team_id}/inbox/reports/{request.report_id}\n"
+ f"Report: {build_report_url(request.team_id, request.report_id, ReportLinkSource.TASK)}\n"
f"Title: {current.title}\n\nSummary:\n{current.summary}"
),
},
diff --git a/products/signals/backend/facade/api.py b/products/signals/backend/facade/api.py
index c5ba1848d9ed..ff1056664ea9 100644
--- a/products/signals/backend/facade/api.py
+++ b/products/signals/backend/facade/api.py
@@ -71,6 +71,10 @@ from products.signals.backend.report_sections import (
ReportSections as ReportSections,
report_sections as report_sections,
)
+from products.signals.backend.report_urls import (
+ ReportLinkSource as ReportLinkSource,
+ report_path as report_path,
+)
from products.signals.backend.scout_harness.create_access import can_create_scout
from products.signals.backend.scout_harness.run_gates import (
# Re-exported so the workflows endpoint can branch on why a fire was refused without reaching
diff --git a/products/signals/backend/github_writeback.py b/products/signals/backend/github_writeback.py
index 6f5fbf88b2f6..3dbfd094c7ec 100644
--- a/products/signals/backend/github_writeback.py
+++ b/products/signals/backend/github_writeback.py
@@ -11,7 +11,6 @@ from __future__ import annotations
from datetime import timedelta
-from django.conf import settings
from django.utils import timezone
import structlog
@@ -23,6 +22,7 @@ from posthog.models.integration import GitHubIntegration
from products.signals.backend.enums import SignalSourceProduct, SignalSourceType
from products.signals.backend.models import SignalReport, SignalReportGithubComment, SignalTeamConfig
+from products.signals.backend.report_urls import ReportLinkSource, build_report_url
logger = structlog.get_logger(__name__)
@@ -203,7 +203,7 @@ def post_report_link_to_github_issues(team: Team, report_id: str, signals: list[
return 0
marker = f"<!-- posthog:signal-report:{report_id} -->"
- body = _comment_body(f"{settings.SITE_URL}/project/{team.pk}/inbox/reports/{report_id}", marker)
+ body = _comment_body(build_report_url(team.pk, report_id, ReportLinkSource.GITHUB_COMMENT), marker)
integrations: dict[str, GitHubIntegration | None] = {}
posted = sum(
_post_to_issue(
diff --git a/products/signals/backend/implementation_pr.py b/products/signals/backend/implementation_pr.py
index bc95e3f8091e..ddc41e759461 100644
--- a/products/signals/backend/implementation_pr.py
+++ b/products/signals/backend/implementation_pr.py
@@ -7,7 +7,6 @@ from datetime import datetime
from typing import TYPE_CHECKING, Any, Literal
from uuid import NAMESPACE_URL, uuid5
-from django.conf import settings
from django.contrib.postgres.expressions import ArraySubquery
from django.db.models import F, Lookup, Q
@@ -26,6 +25,7 @@ from products.signals.backend.models import (
SignalReportPullRequest,
SignalReportTask,
)
+from products.signals.backend.report_urls import ReportLinkSource, build_report_url
from products.signals.backend.task_run_artefacts import (
NON_PR_BEARING_TASK_RUN_TYPES,
SIGNALS_PRODUCT,
@@ -481,7 +481,7 @@ def _close_implementation_pr(
return False
comment = _pr_close_comment(
reason,
- report_link=f"[linked PostHog report]({settings.SITE_URL}/project/{team_id}/inbox/reports/{report_id})",
+ report_link=f"[linked PostHog report]({build_report_url(team_id, report_id, ReportLinkSource.GITHUB_PR)})",
actor_mention=github_mention_for_user(actor_user_id),
replacement_pr_url=replacement_pr_url,
)
diff --git a/products/signals/backend/pr_origin.py b/products/signals/backend/pr_origin.py
index f40f4080ff43..f0626668eefd 100644
--- a/products/signals/backend/pr_origin.py
+++ b/products/signals/backend/pr_origin.py
@@ -33,6 +33,7 @@ from products.signals.backend.artefact_schemas import (
from products.signals.backend.enums import SIGNAL_SOURCE_PRODUCT_LABELS, SignalSourceProduct
from products.signals.backend.models import SignalReportArtefact
from products.signals.backend.pull_request_body import BodyEditOutcome, edit_pull_request_body
+from products.signals.backend.report_urls import ReportLinkSource, build_report_url
from products.signals.backend.scout_harness.lazy_seed import canonical_skill_names
from products.signals.backend.signal_metadata import (
OriginSource,
@@ -237,7 +238,7 @@ class PullRequestOrigin:
sources = fetch_origin_sources_for_report(team, report_id)
return cls(
report_id=report_id,
- report_url=f"{settings.SITE_URL}/project/{team.pk}/inbox/reports/{report_id}",
+ report_url=build_report_url(team.pk, report_id, ReportLinkSource.GITHUB_PR),
sources=tuple(_source_lines(team.pk, sources)),
issue_references=tuple(
_issue_link(reference, repository) for reference in fetch_source_references_for_report(team, report_id)
diff --git a/products/signals/backend/report_urls.py b/products/signals/backend/report_urls.py
new file mode 100644
index 000000000000..cd3f8985bb1c
--- /dev/null
+++ b/products/signals/backend/report_urls.py
@@ -0,0 +1,32 @@
+"""Links to an inbox report that PostHog writes into other surfaces.
+
+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`.
+"""
+
+from enum import StrEnum
+from uuid import UUID
+
+from posthog.utils import absolute_uri
+
+
+class ReportLinkSource(StrEnum):
+ MCP = "mcp"
+ SLACK = "slack"
+ SLACK_SCOUT = "slack_scout"
+ SCOUT = "scout"
+ GITHUB_COMMENT = "github_comment"
+ GITHUB_PR = "github_pr"
+ TRACKER = "tracker"
+ SUPPORT = "support"
+ TASK = "task"
+ 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}"
+
+
+def build_report_url(team_id: int, report_id: str | UUID, source: ReportLinkSource) -> str:
+ return absolute_uri(report_path(team_id, report_id, source))
diff --git a/products/signals/backend/scout_harness/slack_delivery.py b/products/signals/backend/scout_harness/slack_delivery.py
index 3817df9ecdc7..19eb4075bb78 100644
--- a/products/signals/backend/scout_harness/slack_delivery.py
+++ b/products/signals/backend/scout_harness/slack_delivery.py
@@ -20,6 +20,7 @@ from posthog.slack.formatting import channel_id_from_target, escape_slack_mrkdwn
from posthog.slack.markdown import SLACK_MARKDOWN_TEXT_MAX_LEN, slack_markdown_block
from products.signals.backend.models import SignalReport, SignalScoutEmission, SignalScoutRun
+from products.signals.backend.report_urls import ReportLinkSource, build_report_url
from products.signals.backend.scout_harness.slack_charts import (
ChartRenderBudget,
build_scout_report_chart_blocks,
@@ -309,7 +310,7 @@ def _report_header(report: SignalReport) -> str:
def _report_link_block(report: SignalReport) -> dict:
- report_url = f"{settings.SITE_URL.rstrip('/')}/project/{report.team_id}/inbox/reports/{report.id}"
+ report_url = build_report_url(report.team_id, report.id, ReportLinkSource.SLACK_SCOUT)
return {
"type": "actions",
"elements": [
diff --git a/products/signals/backend/scout_harness/tools/report.py b/products/signals/backend/scout_harness/tools/report.py
index 2b846f2c3077..965bd2e6f77e 100644
--- a/products/signals/backend/scout_harness/tools/report.py
+++ b/products/signals/backend/scout_harness/tools/report.py
@@ -32,7 +32,6 @@ from dataclasses import dataclass
from functools import wraps
from typing import TYPE_CHECKING, Any, ParamSpec, TypeVar, cast
-from django.conf import settings
from django.db import transaction
from django.utils import timezone
@@ -87,6 +86,7 @@ from products.signals.backend.report_metrics import (
metric_batch_error,
)
from products.signals.backend.report_prompts import normalize_suggested_prompts, suggested_prompts_batch_error
+from products.signals.backend.report_urls import ReportLinkSource, build_report_url
from products.signals.backend.scout_harness.prompt import SELF_IMPROVEMENT_REPORT_TITLE_PREFIX
from products.signals.backend.scout_harness.skill_loader import resolve_skill_owner_user_uuids
from products.signals.backend.scout_harness.slack_delivery_queue import queue_configured_scout_slack_delivery
@@ -1651,11 +1651,10 @@ class _ReportForward:
def _report_url(team_id: int, report_id: str | None) -> str | None:
- """Inbox deep link for an authored report, or None when no report exists yet (gate-skipped emit). The
- canonical form used by the Slack inbox notifications (`slack_inbox_notifications.py`)."""
+ """Inbox deep link for an authored report, or None when no report exists yet (gate-skipped emit)."""
if not report_id:
return None
- return f"{settings.SITE_URL}/project/{team_id}/inbox/reports/{report_id}"
+ return build_report_url(team_id, report_id, ReportLinkSource.SCOUT)
def _chart_event_key(chart: ReportChartInput) -> str:
diff --git a/products/signals/backend/slack_inbox_notifications.py b/products/signals/backend/slack_inbox_notifications.py
index 2e76fb612224..939a03d290f6 100644
--- a/products/signals/backend/slack_inbox_notifications.py
+++ b/products/signals/backend/slack_inbox_notifications.py
@@ -49,6 +49,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.slack_formatting import (
is_safe_slack_http_url as _is_safe_http_url,
prepare_slack_markdown as _prepare_markdown,
@@ -358,7 +359,7 @@ def _build_message_blocks(
{
"type": "button",
"text": {"type": "plain_text", "text": "Review in PostHog", "emoji": True},
- "url": f"{settings.SITE_URL}/project/{report.team_id}/inbox/reports/{report.id}",
+ "url": build_report_url(report.team_id, report.id, ReportLinkSource.SLACK),
}
]
blocks.append({"type": "actions", "elements": action_elements})
diff --git a/products/signals/backend/support_writeback.py b/products/signals/backend/support_writeback.py
index be784e4aedfa..f93ff5dd00d2 100644
--- a/products/signals/backend/support_writeback.py
+++ b/products/signals/backend/support_writeback.py
@@ -8,8 +8,6 @@ them to draw on, which closes the loop without putting agent output in front of
from __future__ import annotations
-from django.conf import settings
-
import structlog
from posthog.models import Team
@@ -17,6 +15,7 @@ from posthog.models import Team
from products.conversations.backend.facade import api as conversations_facade
from products.signals.backend.enums import SignalSourceProduct
from products.signals.backend.models import SignalReport
+from products.signals.backend.report_urls import ReportLinkSource, build_report_url
logger = structlog.get_logger(__name__)
@@ -54,7 +53,7 @@ def post_report_findings_to_tickets(team: Team, report_id: str, signals: list[di
if not SignalReport.objects.filter(id=report_id, team_id=team.pk).exists():
return 0
- body = _note_body(f"{settings.SITE_URL}/project/{team.pk}/inbox/{report_id}")
+ body = _note_body(build_report_url(team.pk, report_id, ReportLinkSource.SUPPORT))
posted = 0
for ticket_id in ticket_ids:
diff --git a/products/signals/backend/test/test_auto_start.py b/products/signals/backend/test/test_auto_start.py
index 5c5f3a553edb..66f02f0f29e8 100644
--- a/products/signals/backend/test/test_auto_start.py
+++ b/products/signals/backend/test/test_auto_start.py
@@ -771,7 +771,7 @@ def test_autostart_description_lists_source_issues_only_when_references_exist(so
if not expect_references:
assert "Source issues" not in description
assert "addressing" not in description
- assert "inbox/reports/0198c0de-0000-7000-8000-000000000001).' -" in description
+ assert "inbox/reports/0198c0de-0000-7000-8000-000000000001?link_source=task).' -" in description
def test_autostart_description_opens_the_pr_before_the_simplify_pass():
diff --git a/products/signals/backend/test/test_dismissal_pr_close.py b/products/signals/backend/test/test_dismissal_pr_close.py
index 0fb548a2ab86..05839a004491 100644
--- a/products/signals/backend/test/test_dismissal_pr_close.py
+++ b/products/signals/backend/test/test_dismissal_pr_close.py
@@ -353,7 +353,7 @@ class TestCloseImplementationPrForReport(BaseTest):
if login != "octocat":
assert "@" not in comment_body
# The report link carries the attribution GitHub cannot: it names everyone who acted.
- assert f"/project/{self.team.id}/inbox/reports/{self.report.id})" in comment_body
+ assert f"/project/{self.team.id}/inbox/reports/{self.report.id}?link_source=github_pr)" in comment_body
def test_returns_false_and_skips_github_without_linked_pr(self):
self.assignment.pr_url = None
diff --git a/products/signals/backend/test/test_github_writeback.py b/products/signals/backend/test/test_github_writeback.py
index 6adc6d5eda44..35a4793e158a 100644
--- a/products/signals/backend/test/test_github_writeback.py
+++ b/products/signals/backend/test/test_github_writeback.py
@@ -61,7 +61,7 @@ class TestPostReportLinkToGithubIssues(BaseTest):
comment.assert_called_once()
repository, number, body = comment.call_args.args
assert (repository, number) == ("acme/widgets", 42)
- assert f"/project/{self.team.pk}/inbox/reports/{self.report.id}" in body
+ assert f"/project/{self.team.pk}/inbox/reports/{self.report.id}?link_source=github_comment" in body
def test_comment_carries_no_report_content(self):
# The comment is public on the issue thread while the report is behind the project's access
diff --git a/products/signals/backend/test/test_scout_report_api.py b/products/signals/backend/test/test_scout_report_api.py
index 57538ab522ff..e6bf827dd985 100644
--- a/products/signals/backend/test/test_scout_report_api.py
+++ b/products/signals/backend/test/test_scout_report_api.py
@@ -2031,7 +2031,9 @@ class TestScoutReportAPI(APIBaseTest):
assert forward.kwargs["token"] == self.team.api_token
assert forward.kwargs["process_person_profile"] is False
assert forward.kwargs["distinct_id"] == f"signals_scout:{run.skill_name}"
- expected_url = None if expected_outcome == "gate_skipped" else f"/inbox/reports/{body['report_id']}"
+ expected_url = (
+ None if expected_outcome == "gate_skipped" else f"/inbox/reports/{body['report_id']}?link_source=scout"
+ )
if expected_url is None:
assert forward.kwargs["properties"]["report_url"] is None
else:
@@ -2062,7 +2064,9 @@ class TestScoutReportAPI(APIBaseTest):
)
assert forward.kwargs["token"] == self.team.api_token
assert forward.kwargs["process_person_profile"] is False
- assert forward.kwargs["properties"]["report_url"].endswith(f"/inbox/reports/{created['report_id']}")
+ assert forward.kwargs["properties"]["report_url"].endswith(
+ f"/inbox/reports/{created['report_id']}?link_source=scout"
+ )
assert props["run_id"] == str(run.id)
assert forward.kwargs["distinct_id"] == f"signals_scout:{run.skill_name}"
# Ingestion dedupes on this uuid. If its key drifts, an edit retried across a deploy fires twice.
diff --git a/products/signals/backend/test/test_scout_slack_delivery.py b/products/signals/backend/test/test_scout_slack_delivery.py
index 8f27df4c844a..eabf442a236d 100644
--- a/products/signals/backend/test/test_scout_slack_delivery.py
+++ b/products/signals/backend/test/test_scout_slack_delivery.py
@@ -219,7 +219,7 @@ class TestScoutSlackDelivery(BaseTest):
assert "[#93147 fix(checkout): retry 500s](https://example.com/pull/93147)" in markdown
actions_block = next(block for block in call["blocks"] if block["type"] == "actions")
assert actions_block["elements"][0]["url"] == (
- f"{settings.SITE_URL}/project/{self.team.id}/inbox/reports/{report.id}"
+ f"{settings.SITE_URL}/project/{self.team.id}/inbox/reports/{report.id}?link_source=slack_scout"
)
assert call["blocks"][-1]["type"] == "context"
assert fake_client.chat_postMessage.call_count == 1
@@ -270,7 +270,7 @@ class TestScoutSlackDelivery(BaseTest):
assert "failed for many users" not in markdown
actions_block = next(block for block in call["blocks"] if block["type"] == "actions")
assert actions_block["elements"][0]["url"] == (
- f"{settings.SITE_URL}/project/{self.team.id}/inbox/reports/{report.id}"
+ f"{settings.SITE_URL}/project/{self.team.id}/inbox/reports/{report.id}?link_source=slack_scout"
)
def test_enqueue_omits_edit_note_kwarg_when_unset(self) -> None:
diff --git a/products/signals/backend/test/test_slack_inbox_notifications.py b/products/signals/backend/test/test_slack_inbox_notifications.py
index 734d3faa3861..4751d095a088 100644
--- a/products/signals/backend/test/test_slack_inbox_notifications.py
+++ b/products/signals/backend/test/test_slack_inbox_notifications.py
@@ -120,7 +120,7 @@ def test_build_message_blocks_includes_recipient_and_open_in_posthog_button() ->
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"
+ assert buttons[0]["url"] == f"{settings.SITE_URL}/project/42/inbox/reports/report-uuid?link_source=slack"
assert text == "Report (P1): Checkout errors spiked"
@@ -356,7 +356,9 @@ def test_dispatch_sends_to_configured_reviewer(org_and_team, target, expected_co
else:
assert "Suggested reviewers" not in context_text
assert all("<@" not in t for t in _plain_text_block_texts(blocks))
- assert blocks[3]["elements"][0]["url"] == f"{settings.SITE_URL}/project/{team.id}/inbox/reports/{report.id}"
+ assert blocks[3]["elements"][0]["url"] == (
+ f"{settings.SITE_URL}/project/{team.id}/inbox/reports/{report.id}?link_source=slack"
+ )
@pytest.mark.django_db
diff --git a/products/signals/backend/test/test_support_writeback.py b/products/signals/backend/test/test_support_writeback.py
index 87db5762839f..e163ff59c3ee 100644
--- a/products/signals/backend/test/test_support_writeback.py
+++ b/products/signals/backend/test/test_support_writeback.py
@@ -49,7 +49,7 @@ class TestPostReportFindingsToTickets(BaseTest):
note = _ticket_notes(self.team, self.ticket).get()
assert note.item_context["is_private"] is True
assert note.item_context["author_type"] == "AI"
- assert f"/project/{self.team.pk}/inbox/{self.report.id}" in note.content
+ assert f"/project/{self.team.pk}/inbox/reports/{self.report.id}?link_source=support" in note.content
def test_note_carries_no_report_content(self):
# Comments authorize as `comment` while reports authorize as `task`, so a teammate with ticket
diff --git a/products/signals/backend/test/test_tracker_issues.py b/products/signals/backend/test/test_tracker_issues.py
index 2d85c9f13560..2161a0acf4f3 100644
--- a/products/signals/backend/test/test_tracker_issues.py
+++ b/products/signals/backend/test/test_tracker_issues.py
@@ -315,7 +315,7 @@ def test_tracker_issue_comment_names_the_actor_and_never_blocks_the_close(team,
close_issue.assert_called_once_with("web", 12, completed=False)
body = comment.call_args.args[2]
assert "@octocat closed the" in body
- assert f"/project/{team.id}/inbox/reports/{report.id})" in body
+ assert f"/project/{team.id}/inbox/reports/{report.id}?link_source=tracker)" in body
@pytest.mark.django_db
diff --git a/products/signals/backend/tracker_issues.py b/products/signals/backend/tracker_issues.py
index 219b5b2d09db..42280930214b 100644
--- a/products/signals/backend/tracker_issues.py
+++ b/products/signals/backend/tracker_issues.py
@@ -13,7 +13,6 @@ import re
from datetime import timedelta
from typing import Any
-from django.conf import settings
from django.utils import timezone
import structlog
@@ -33,6 +32,7 @@ from posthog.models.integration import (
from products.signals.backend.github_actor import github_mention_for_user
from products.signals.backend.models import SignalReport, SignalReportTrackerIssue, SignalTeamConfig
from products.signals.backend.pull_request_body import BodyEditOutcome, edit_pull_request_body
+from products.signals.backend.report_urls import ReportLinkSource, build_report_url
logger = structlog.get_logger(__name__)
@@ -219,7 +219,7 @@ def create_tracker_issue_for_report(
if tracker is None:
return SignalReportTrackerIssue.objects.for_team(team_id).filter(report_id=report_id).first()
- report_url = f"{settings.SITE_URL}/project/{team_id}/inbox/reports/{report_id}"
+ report_url = build_report_url(team_id, report_id, ReportLinkSource.TRACKER)
try:
external_context = _create_provider_issue(
target,
@@ -405,7 +405,7 @@ def close_tracker_issue_for_report(
if tracker is None or tracker.closed_at is not None:
return False
- report_url = f"{settings.SITE_URL}/project/{team_id}/inbox/reports/{report_id}"
+ report_url = build_report_url(team_id, report_id, ReportLinkSource.TRACKER)
_comment_before_close(
tracker,
report_link=f"[linked PostHog report]({report_url})",
diff --git a/products/signals/frontend/inbox/inboxAnalytics.ts b/products/signals/frontend/inbox/inboxAnalytics.ts
index ef4ae9c2d684..62c13f2b3196 100644
--- a/products/signals/frontend/inbox/inboxAnalytics.ts
+++ b/products/signals/frontend/inbox/inboxAnalytics.ts
@@ -98,6 +98,35 @@ export type InboxSelectionEntryMethod = 'long_press' | 'meta_click' | 'shift_cli
/** How a report detail was opened. `triage` is the open-report shortcut in triage mode. */
export type InboxReportOpenMethod = 'click' | 'deeplink' | 'triage' | 'unknown'
+/**
+ * The surface that wrote a report link, from its `link_source` query param. Must match
+ * `ReportLinkSource` in `products/signals/backend/report_urls.py`.
+ */
+export const INBOX_REPORT_LINK_SOURCES = [
+ 'mcp',
+ 'slack',
+ 'slack_scout',
+ 'scout',
+ 'github_comment',
+ 'github_pr',
+ 'tracker',
+ 'support',
+ 'task',
+ 'today',
+] as const
+
+/** `other` is a `source` value outside the fixed set, so a typo or a hand-edited link stays countable. */
+export type InboxReportLinkSource = (typeof INBOX_REPORT_LINK_SOURCES)[number] | 'other'
+
+export function parseInboxReportLinkSource(value: unknown): InboxReportLinkSource | null {
+ if (value === undefined || value === null || value === '') {
+ return null
+ }
+ return (INBOX_REPORT_LINK_SOURCES as readonly unknown[]).includes(value)
+ ? (value as InboxReportLinkSource)
+ : 'other'
+}
+
/**
* How a report detail was closed. `page_unload` is a tab close or hard page navigation: the scene
* never unmounts, so it flushes on `pagehide` instead of the `unmount` path.
@@ -438,6 +467,7 @@ export function captureInboxReportOpened(
params: {
report: SignalReport
openMethod: InboxReportOpenMethod
+ linkSource: InboxReportLinkSource | null
previousReportId: string | null
rank: number | null
listSize: number | null
@@ -453,6 +483,7 @@ export function captureInboxReportOpened(
status: params.report.status ?? null,
source_products: params.report.source_products ?? [],
open_method: params.openMethod,
+ link_source: params.linkSource,
previous_report_id: params.previousReportId,
rank: params.rank,
list_size: params.listSize,
diff --git a/products/signals/frontend/inbox/inboxSceneLogic.test.ts b/products/signals/frontend/inbox/inboxSceneLogic.test.ts
index 500e456c655d..54a807b9657c 100644
--- a/products/signals/frontend/inbox/inboxSceneLogic.test.ts
+++ b/products/signals/frontend/inbox/inboxSceneLogic.test.ts
@@ -400,6 +400,47 @@ describe('inboxSceneLogic routing', () => {
expect(openMethod).toBe(expected)
})
+ // 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.
+ 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' },
+ {
+ name: 'an unknown source',
+ source: 'carrier-pigeon',
+ visitedList: false,
+ method: 'deeplink',
+ linkSource: 'other',
+ },
+ { 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 },
+ ])(
+ 'a report link with $name opens as $method with link source $linkSource',
+ async ({ source, visitedList, method, linkSource }) => {
+ mountWithRedesign(true)
+ if (visitedList) {
+ router.actions.push(urls.inbox('reports'))
+ }
+ const url = combineUrl(
+ urls.inboxReport('reports', 'r1'),
+ source ? { link_source: source, source: 'github' } : { source: 'github' }
+ ).url
+
+ let payload: { openMethod?: string; linkSource?: string | null } = {}
+ await expectLogic(logic, () => router.actions.push(url)).toDispatchActions([
+ (action: any) => {
+ if (action.type !== logic.actionTypes.setSelectedReportId) {
+ return false
+ }
+ payload = action.payload
+ return true
+ },
+ ])
+ expect(payload).toMatchObject({ openMethod: method, linkSource })
+ expect(router.values.searchParams).toEqual({ source: 'github' })
+ }
+ )
+
// A rank read at open time is null on a cold load, and joins to no impression row. The event is
// then captured after the wait, so it also has to carry the moment the report opened: a scroll
// or an action taken during the wait would otherwise read earlier than the open.
@@ -421,7 +462,7 @@ describe('inboxSceneLogic routing', () => {
listLogic.mount()
listLogic.actions.loadReports()
- logic.actions.setSelectedReportId('r1')
+ logic.actions.setSelectedReportId('r1', 'deeplink', 'slack')
const beforeOpen = Date.now()
logic.actions.loadSelectedReportSuccess(report)
const afterOpen = Date.now()
@@ -429,7 +470,12 @@ describe('inboxSceneLogic routing', () => {
await waitForOpenRankRetry()
- expect(openedEvents(captureSpy)[0]).toMatchObject({ rank: 1, list_size: 1 })
+ expect(openedEvents(captureSpy)[0]).toMatchObject({
+ rank: 1,
+ list_size: 1,
+ open_method: 'deeplink',
+ link_source: 'slack',
+ })
const stampedAt = (openedCalls(captureSpy)[0][2] as CaptureOptions | undefined)?.timestamp?.getTime()
expect(stampedAt).toBeGreaterThanOrEqual(beforeOpen)
expect(stampedAt).toBeLessThanOrEqual(afterOpen)
diff --git a/products/signals/frontend/inbox/inboxSceneLogic.ts b/products/signals/frontend/inbox/inboxSceneLogic.ts
index f48773f89992..10f97ad3dbb4 100644
--- a/products/signals/frontend/inbox/inboxSceneLogic.ts
+++ b/products/signals/frontend/inbox/inboxSceneLogic.ts
@@ -35,7 +35,9 @@ import {
captureInboxReportOpened,
captureInboxReportScrolled,
InboxReportCloseMethod,
+ InboxReportLinkSource,
InboxReportOpenMethod,
+ parseInboxReportLinkSource,
} from './inboxAnalytics'
import { inboxBulkActionsLogic } from './logics/inboxBulkActionsLogic'
import { inboxFiltersLogic } from './logics/inboxFiltersLogic'
@@ -236,6 +238,16 @@ 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 withoutLinkSource(searchParams: Record<string, any>): Record<string, any> {
+ const { link_source: _linkSource, ...rest } = searchParams
+ return rest
+}
+
function mountedReportLists(): ReturnType<typeof reportListLogic.build>[] {
return (Object.keys(INBOX_REPORT_SECTION_LIST_PARAMS) as InboxReportSectionKey[]).flatMap((sectionKey) => {
const mounted = reportListLogic.findMounted({
@@ -338,6 +350,7 @@ function captureOpenWhenRanked(
cache: Record<string, any>,
tracking: InboxOpenTracking,
openMethod: InboxReportOpenMethod,
+ linkSource: InboxReportLinkSource | null,
flatList: boolean
): void {
const previousReportId = cache.previousReportId ?? null
@@ -350,6 +363,7 @@ function captureOpenWhenRanked(
{
report: tracking.report,
openMethod,
+ linkSource,
previousReportId,
rank: resolved.rank,
listSize: resolved.listSize,
@@ -583,9 +597,11 @@ export interface inboxSceneLogicActions {
}
setSelectedReportId: (
id: string | null,
- openMethod?: InboxReportOpenMethod
+ openMethod?: InboxReportOpenMethod,
+ linkSource?: InboxReportLinkSource | null
) => {
id: string | null
+ linkSource: InboxReportLinkSource | null
openMethod: InboxReportOpenMethod
}
setSelectedScoutSkillName: (
@@ -643,9 +659,14 @@ export const inboxSceneLogic = kea<inboxSceneLogicType>([
})),
actions({
- setSelectedReportId: (id: string | null, openMethod: InboxReportOpenMethod = 'unknown') => ({
+ setSelectedReportId: (
+ id: string | null,
+ openMethod: InboxReportOpenMethod = 'unknown',
+ linkSource: InboxReportLinkSource | null = null
+ ) => ({
id,
openMethod,
+ linkSource,
}),
// 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.
@@ -988,7 +1009,7 @@ export const inboxSceneLogic = kea<inboxSceneLogicType>([
actions.setActiveTab('reports')
}
},
- setSelectedReportId: ({ id, openMethod }) => {
+ setSelectedReportId: ({ id, openMethod, linkSource }) => {
// Close the previously open report (if any) before opening/clearing. `next_report` when
// switching straight to another report, `deselected` when returning to the list.
const open: InboxOpenTracking | undefined = cache.openTracking
@@ -1012,6 +1033,7 @@ export const inboxSceneLogic = kea<inboxSceneLogicType>([
clearScratchpadSearch()
// The open method is resolved once the authoritative record lands in loadSelectedReportSuccess.
cache.pendingOpenMethod = openMethod
+ cache.pendingLinkSource = linkSource
// A report and a scout detail are mutually exclusive full-width views.
if (values.selectedScoutSkillName !== null) {
actions.setSelectedScoutSkillName(null)
@@ -1049,9 +1071,11 @@ export const inboxSceneLogic = kea<inboxSceneLogicType>([
cache,
tracking,
(cache.pendingOpenMethod as InboxReportOpenMethod | undefined) ?? 'unknown',
+ (cache.pendingLinkSource as InboxReportLinkSource | null | undefined) ?? null,
values.isRedesign
)
cache.pendingOpenMethod = undefined
+ cache.pendingLinkSource = undefined
// Best-effort server-side view record: consumption evidence that keeps the authoring
// scout from being auto-paused as ignored. The analytics event above stays the rich
// record (rank, open method, dwell), so a failure here is swallowed.
@@ -1224,9 +1248,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 }
- : router.values.searchParams,
+ : withoutLinkSource(router.values.searchParams),
router.values.hashParams,
- { replace: false },
+ // Replace, so Back does not return to the link URL and its `link_source`.
+ { replace: hasLinkSource(router.values.searchParams) },
],
setSelectedScoutSkillName: ({ findingId }) => [
inboxSurfaceUrl(values),
@@ -1447,14 +1472,20 @@ export const inboxSceneLogic = kea<inboxSceneLogicType>([
if (values.selectedReportId !== reportId) {
// A `back` pointing at triage means the open came from the triage card's "Full
// report" link, which navigates by URL rather than through `openCurrent`; attribute
- // it to triage so the metric isn't split with plain list clicks. Otherwise: a first
- // route before any list URL was seen is a cold deep-link, else an in-app click.
+ // it to triage so the metric isn't split with plain list clicks. Otherwise: a link
+ // PostHog wrote, or a first route before any list URL was seen, is a deep-link,
+ // else an in-app click. A tab that already saw the list can still open a link.
const fromTriage =
typeof searchParams.back === 'string' && searchParams.back.startsWith(urls.inboxTriage())
+ const linkSource = fromTriage ? null : parseInboxReportLinkSource(searchParams.link_source)
actions.setSelectedReportId(
reportId,
- fromTriage ? 'triage' : hasVisitedInboxList() ? 'click' : 'deeplink'
+ fromTriage ? 'triage' : linkSource !== null || !hasVisitedInboxList() ? 'deeplink' : 'click',
+ linkSource
)
+ } else if (hasLinkSource(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)
}
},
}
diff --git a/products/signals/frontend/inbox/logics/inboxTriageLogic.ts b/products/signals/frontend/inbox/logics/inboxTriageLogic.ts
index 5267f561abbe..41e1183a9e96 100644
--- a/products/signals/frontend/inbox/logics/inboxTriageLogic.ts
+++ b/products/signals/frontend/inbox/logics/inboxTriageLogic.ts
@@ -65,9 +65,11 @@ export interface inboxTriageLogicValues {
export interface inboxTriageLogicActions {
setSelectedReportId: (
id: string | null,
- openMethod?: import('../inboxAnalytics').InboxReportOpenMethod | undefined
+ openMethod?: import('../inboxAnalytics').InboxReportOpenMethod | undefined,
+ linkSource?: null | import('../inboxAnalytics').InboxReportLinkSource | undefined
) => {
id: string | null
+ linkSource: null | import('../inboxAnalytics').InboxReportLinkSource
openMethod: import('../inboxAnalytics').InboxReportOpenMethod
} // inboxSceneLogic
createPrFromReport: (
diff --git a/products/today/backend/logic/fact_sheet.py b/products/today/backend/logic/fact_sheet.py
index a24e48b1565f..5e4c7b9520c0 100644
--- a/products/today/backend/logic/fact_sheet.py
+++ b/products/today/backend/logic/fact_sheet.py
@@ -63,7 +63,7 @@ def fact_sheet_for_reports(reports: Sequence[signals.BriefingReport], team_id: i
source=ItemSource.SELF_DRIVING,
reason=_REASON_FOR_RELATION[report.relation],
title=report.title,
- url=f"/project/{team_id}/inbox/{report.report_id}",
+ url=signals.report_path(team_id, report.report_id, signals.ReportLinkSource.TODAY),
rank=rank,
source_product=report.source_products[0] if report.source_products else None,
facts=_report_facts(report),
diff --git a/products/today/backend/tests/test_generate.py b/products/today/backend/tests/test_generate.py
index c31fbb5033f8..cbbc51280382 100644
--- a/products/today/backend/tests/test_generate.py
+++ b/products/today/backend/tests/test_generate.py
@@ -135,8 +135,8 @@ class TestWriteBriefing(TodayTeamScopedTestMixin, BaseTest):
self.briefing.refresh_from_db()
assert (self.briefing.status, self.briefing.writer) == (BriefingStatus.READY, BriefingWriter.AGENT)
assert [(item["key"], item["reason"], item["url"]) for item in self.briefing.facts["items"]] == [
- ("report:b", "suggested_reviewer", f"/project/{self.team.id}/inbox/b"),
- ("report:a", "waiting_for_you", f"/project/{self.team.id}/inbox/a"),
+ ("report:b", "suggested_reviewer", f"/project/{self.team.id}/inbox/reports/b?link_source=today"),
+ ("report:a", "waiting_for_you", f"/project/{self.team.id}/inbox/reports/a?link_source=today"),
]
content = self.briefing.content
assert content["headline"] == "Two reports need your input"