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): link Slack-mention tasks back to the inbox report (#103115)

posthog[bot]dbcd795af7bb
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index 7a8b9018500c..dde1e69fe640 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -349,6 +349,7 @@ rules:
|SignalReportPullRequest
|SignalReportAssignment
|SignalReportRefund
+ |SignalReportSlackThread
|SignalReportTask
|SignalReportTrackerIssue
|SignalRepositoryAreaActivity
@@ -765,6 +766,7 @@ rules:
|SignalReportPullRequest
|SignalReportAssignment
|SignalReportRefund
+ |SignalReportSlackThread
|SignalReportTask
|SignalReportTrackerIssue
|SignalRepositoryAreaActivity
diff --git a/posthog/temporal/ai/slack_app/activities/task_creation.py b/posthog/temporal/ai/slack_app/activities/task_creation.py
index b1edfbe96564..e0a6e09ad814 100644
--- a/posthog/temporal/ai/slack_app/activities/task_creation.py
+++ b/posthog/temporal/ai/slack_app/activities/task_creation.py
@@ -547,6 +547,7 @@ def create_posthog_code_task_for_repo_activity(
) -> None:
from posthog.models.integration import Integration, SlackIntegration
+ from products.signals.backend.facade import api as signals_facade
from products.slack_app.backend.models import SlackThreadTaskMapping
from products.slack_app.backend.services.slack_conversations import resolve_conversation_type
from products.slack_app.backend.slack_thread import SlackThreadContext
@@ -560,6 +561,16 @@ def create_posthog_code_task_for_repo_activity(
)
slack = SlackIntegration(integration)
+ # A report notification invites the reader to reply in its thread, so a mention there is the
+ # team discussing that report. Resolved from the context thread, which on a fork is the source
+ # thread the requester pointed at rather than the DM the agent answers in.
+ signal_report_id = signals_facade.report_id_for_slack_thread(
+ slack_workspace_id=inputs.slack_team_id,
+ team_id=integration.team_id,
+ channel=inputs.fork_source_channel or channel,
+ thread_ts=inputs.fork_source_thread_ts or thread_ts,
+ )
+
# Idempotency guard: this activity runs under a retry policy but its body is
# not idempotent — a retry after the mapping write would create a duplicate
# task + run, re-upload attachments to it, and repoint the mapping, orphaning
@@ -567,11 +578,19 @@ def create_posthog_code_task_for_repo_activity(
# concurrent duplicate mention) already created the task; a run left QUEUED
# by a crash before the workflow start is recovered by the orphaned-run
# janitor sweep.
- if SlackThreadTaskMapping.objects.filter(
+ existing_mapping = SlackThreadTaskMapping.objects.filter(
integration_id=inputs.integration_id,
channel=channel,
thread_ts=thread_ts,
- ).exists():
+ ).first()
+ if existing_mapping is not None:
+ if signal_report_id:
+ tasks_facade.link_slack_task_to_report(
+ team_id=integration.team_id,
+ task_id=str(existing_mapping.task_id),
+ report_id=signal_report_id,
+ user_id=user_id,
+ )
logger.info(
"posthog_code_task_creation_skipped_existing_mapping",
channel=channel,
@@ -781,6 +800,13 @@ def create_posthog_code_task_for_repo_activity(
"conversation_type": resolve_conversation_type(slack, event, channel),
},
)
+ if signal_report_id:
+ tasks_facade.link_slack_task_to_report(
+ team_id=integration.team_id,
+ task_id=str(created.task_id),
+ report_id=signal_report_id,
+ user_id=user_id,
+ )
# Track the workflow to link Temporal jobs to Slack threads
state_updates: dict[str, Any] = {
"slack_mention_workflow_id": derive_mention_workflow_id(inputs),
diff --git a/products/signals/backend/facade/api.py b/products/signals/backend/facade/api.py
index 6a346b60267c..54a4153225ce 100644
--- a/products/signals/backend/facade/api.py
+++ b/products/signals/backend/facade/api.py
@@ -20,6 +20,11 @@ from posthog.models import Team
from posthog.sync import database_sync_to_async
from posthog.temporal.common.client import async_connect
+from products.signals.backend.artefact_schemas import (
+ # Re-exported so the Slack mention handler can label the task it starts from a report's
+ # notification thread without naming the relationship vocabulary itself.
+ TASK_RUN_TYPE_DISCUSSION as TASK_RUN_TYPE_DISCUSSION,
+)
from products.signals.backend.contracts import DIRECT_STEERABLE_SOURCES, SIGNAL_VARIANT_LOOKUP, SignalRemediation
from products.signals.backend.enums import SIGNAL_SOURCE_PRODUCT_LABELS, SignalSourceProduct
from products.signals.backend.models import SignalReport, SignalScoutConfig, SignalScoutRun, SignalSourceConfig
@@ -163,6 +168,44 @@ def dismiss_report_from_slack(
return suppress_report_from_slack(team_id, report_id, slack_user_id=slack_user_id, user_id=user_id)
+def report_id_for_slack_thread(*, team_id: int, slack_workspace_id: str, channel: str, thread_ts: str) -> str | None:
+ """Facade entrypoint for the Slack mention handler. See slack_report_threads.report_id_for_slack_thread."""
+ from products.signals.backend.slack_report_threads import (
+ report_id_for_slack_thread as report_id_for_slack_thread_impl, # noqa: PLC0415 — avoids importing model layer at facade import time
+ )
+
+ return report_id_for_slack_thread_impl(
+ team_id=team_id, slack_workspace_id=slack_workspace_id, channel=channel, thread_ts=thread_ts
+ )
+
+
+def report_team_id_for_slack_thread(
+ *, team_ids: Sequence[int], slack_workspace_id: str, channel: str, thread_ts: str
+) -> int | None:
+ from products.signals.backend.slack_report_threads import ( # noqa: PLC0415 — avoids importing model layer at facade import time
+ report_team_id_for_slack_thread as report_team_id_for_slack_thread_impl,
+ )
+
+ return report_team_id_for_slack_thread_impl(
+ team_ids=team_ids, slack_workspace_id=slack_workspace_id, channel=channel, thread_ts=thread_ts
+ )
+
+
+def record_slack_report_discussion(*, team_id: int, report_id: str, task_id: str, user_id: int) -> None:
+ """Record a discussion started by a verified Slack user after its thread mapping is saved."""
+ from products.signals.backend.models import SignalReport, SignalReportAction
+ from products.signals.backend.task_run_artefacts import record_report_task
+
+ SignalReport.objects.get(team_id=team_id, id=report_id)
+ record_report_task(team_id=team_id, report_id=report_id, task_id=task_id, relationship=TASK_RUN_TYPE_DISCUSSION)
+ SignalReportAction.record(
+ team_id=team_id,
+ report_id=report_id,
+ user_id=user_id,
+ action_type=SignalReportAction.ActionType.SLACK_DISCUSSION,
+ )
+
+
def persisted_repo_selection(report_id: str) -> "RepoSelectionResult | None":
"""Facade entrypoint for a report's latest repo selection. See select_repo.persisted_repo_selection."""
from products.signals.backend.report_generation.select_repo import (
@@ -753,10 +796,9 @@ def forward_report_discussion_note(
relationship forwards, so an implementation or research kickoff never leaves a note. Best-effort:
returns the note id, or None when nothing was forwarded.
"""
- from products.signals.backend.artefact_schemas import ( # noqa: PLC0415 — keeps the notes stack off this module's import path
- TASK_RUN_TYPE_DISCUSSION,
+ from products.signals.backend.discussion_notes import ( # noqa: PLC0415 — keeps the notes stack off this module's import path
+ forward_discussion_note,
)
- from products.signals.backend.discussion_notes import forward_discussion_note # noqa: PLC0415 — same
if relationship != TASK_RUN_TYPE_DISCUSSION or not report_id:
return None
diff --git a/products/signals/backend/migrations/0146_signalreportslackthread.py b/products/signals/backend/migrations/0146_signalreportslackthread.py
new file mode 100644
index 000000000000..e7fcfa56c449
--- /dev/null
+++ b/products/signals/backend/migrations/0146_signalreportslackthread.py
@@ -0,0 +1,76 @@
+# Generated by Django 5.2.17 on 2026-09-18 16:47
+
+import django.db.models.manager
+import django.db.models.deletion
+from django.db import migrations, models
+
+import posthog.uuidt
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1368_sessionrecording_untrack_lts_fields"),
+ ("signals", "0145_untrack_signalscoutemission_confidence"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="SignalReportSlackThread",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("slack_workspace_id", models.CharField(max_length=64)),
+ ("channel", models.CharField(max_length=64)),
+ ("thread_ts", models.CharField(max_length=64)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ (
+ "integration",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to="posthog.integration",
+ ),
+ ),
+ (
+ "report",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="slack_threads",
+ to="signals.signalreport",
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "verbose_name": "Signal report Slack thread",
+ "verbose_name_plural": "Signal report Slack threads",
+ "default_manager_name": "all_teams",
+ "constraints": [
+ models.UniqueConstraint(
+ fields=("slack_workspace_id", "channel", "thread_ts"),
+ name="signals_report_slack_thread_unique",
+ )
+ ],
+ },
+ managers=[
+ ("all_teams", django.db.models.manager.Manager()),
+ ],
+ ),
+ ]
diff --git a/products/signals/backend/migrations/0147_alter_signalreportaction_type.py b/products/signals/backend/migrations/0147_alter_signalreportaction_type.py
new file mode 100644
index 000000000000..7a2743a13dac
--- /dev/null
+++ b/products/signals/backend/migrations/0147_alter_signalreportaction_type.py
@@ -0,0 +1,24 @@
+# Generated by Django 5.2.17 on 2026-09-22 14:46
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("signals", "0146_signalreportslackthread"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="signalreportaction",
+ name="type",
+ field=models.CharField(
+ choices=[
+ ("view", "View"),
+ ("feedback", "Feedback"),
+ ("slack_discussion", "Slack Discussion"),
+ ],
+ max_length=20,
+ ),
+ ),
+ ]
diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txt
index 367311cd45cf..e50982bfab95 100644
--- a/products/signals/backend/migrations/max_migration.txt
+++ b/products/signals/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0145_untrack_signalscoutemission_confidence
+0147_alter_signalreportaction_type
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.py
index a8a85e84f986..af570c39fbf6 100644
--- a/products/signals/backend/models.py
+++ b/products/signals/backend/models.py
@@ -1039,6 +1039,46 @@ class SignalReportGithubComment(TeamScopedRootMixin, UUIDModel):
verbose_name_plural = "Signal report GitHub comments"
+class SignalReportSlackThread(UUIDModel):
+ """The Slack thread a report notification started, so a reply in it resolves back to the report.
+
+ A notification invites the reader to reply in the thread and mention PostHog, which starts a
+ task. Without this row that task has no way back to the report it discusses, so the work never
+ reaches the report's own timeline.
+ """
+
+ objects = EnvironmentScopedManager()
+ all_teams = models.Manager() # noqa: DJ012
+
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False, related_name="+")
+ report = models.ForeignKey(SignalReport, on_delete=models.CASCADE, related_name="slack_threads")
+ # SET_NULL rather than CASCADE: a disconnected workspace must not erase the link between a
+ # report and the task somebody already started from its thread.
+ integration = models.ForeignKey(
+ "posthog.Integration", on_delete=models.SET_NULL, null=True, blank=True, related_name="+"
+ )
+ # The resolved Slack channel id, so a config that names the channel differently still matches.
+ slack_workspace_id = models.CharField(max_length=64)
+ channel = models.CharField(max_length=64)
+ # Slack `ts` of the notification message, which is also its thread's root.
+ thread_ts = models.CharField(max_length=64)
+
+ created_at = models.DateTimeField(auto_now_add=True)
+
+ class Meta:
+ default_manager_name = "all_teams"
+ constraints = [
+ # One Slack message is one thread, and a thread is about at most one report. Keyed
+ # without the team so a second project connected to the same workspace cannot claim a
+ # thread another project's report already owns.
+ models.UniqueConstraint(
+ fields=["slack_workspace_id", "channel", "thread_ts"], name="signals_report_slack_thread_unique"
+ ),
+ ]
+ verbose_name = "Signal report Slack thread"
+ verbose_name_plural = "Signal report Slack threads"
+
+
class SignalReportPullRequest(TeamScopedRootMixin, UUIDModel):
State = SignalReportAssignment.PrState
@@ -1798,6 +1838,7 @@ class SignalReportAction(TeamScopedRootMixin, UUIDModel):
VIEW = "view"
# The thumbs rating at the end of the report body ("Was this report useful?").
FEEDBACK = "feedback"
+ SLACK_DISCUSSION = "slack_discussion"
# See SignalReportRefund.all_teams for rationale.
all_teams = models.Manager() # noqa: DJ012
diff --git a/products/signals/backend/scout_harness/slack_delivery.py b/products/signals/backend/scout_harness/slack_delivery.py
index ee7fb31a9274..bbdc9e99c09d 100644
--- a/products/signals/backend/scout_harness/slack_delivery.py
+++ b/products/signals/backend/scout_harness/slack_delivery.py
@@ -36,6 +36,7 @@ from products.signals.backend.slack_formatting import (
split_markdown_by_headings,
strip_chart_references,
)
+from products.signals.backend.slack_report_threads import record_report_slack_thread
from products.slack_app.backend.facade.api import slack_followup_invite
logger = structlog.get_logger(__name__)
@@ -739,6 +740,17 @@ def post_scout_report_to_slack(
raise
thread_ts = response.get("ts")
+ if thread_ts:
+ record_report_slack_thread(
+ slack_workspace_id=integration.integration_id,
+ team_id=report.team_id,
+ report_id=str(report.id),
+ integration_id=integration.id,
+ # The conversation Slack posted into, which for a member target is the direct message
+ # it opened rather than the id we sent. An inbound mention names the conversation.
+ channel=str(response.get("channel") or channel_id),
+ thread_ts=str(thread_ts),
+ )
if threaded:
_post_scout_report_thread_replies(
client,
diff --git a/products/signals/backend/slack_inbox_notifications.py b/products/signals/backend/slack_inbox_notifications.py
index 8fd0da44b841..eab058366a46 100644
--- a/products/signals/backend/slack_inbox_notifications.py
+++ b/products/signals/backend/slack_inbox_notifications.py
@@ -52,6 +52,7 @@ from products.signals.backend.slack_formatting import (
strip_chart_references as _strip_chart_references,
)
from products.signals.backend.slack_notification_targets import is_slack_member_target, lookup_slack_user_id_by_email
+from products.signals.backend.slack_report_threads import record_report_slack_thread
from products.slack_app.backend.facade.api import slack_followup_invite
# Actionability values shown in the inbox Reports tab. Slack notifications mirror that tab, so a
@@ -698,6 +699,20 @@ def _deliver_route_notification(
response = slack.client.chat_postMessage(channel=channel_id, blocks=blocks, text=text)
delivered = True
thread_ts = response.get("ts") if hasattr(response, "get") else None
+ # A member target opens a direct message, so the conversation Slack posted into is not the
+ # id we sent. An inbound mention names the conversation, so that is what the link records.
+ posted_channel = response.get("channel") if hasattr(response, "get") else None
+ if thread_ts:
+ # Recorded before the evidence replies, so a failure posting those still leaves the
+ # thread resolvable back to the report.
+ record_report_slack_thread(
+ slack_workspace_id=route.integration.integration_id,
+ team_id=report.team_id,
+ report_id=str(report.id),
+ integration_id=route.integration.id,
+ channel=str(posted_channel or channel_id),
+ thread_ts=str(thread_ts),
+ )
if signals and thread_ts:
_post_signal_evidence_thread(slack, channel_id, str(thread_ts), signals)
except Exception:
diff --git a/products/signals/backend/slack_report_threads.py b/products/signals/backend/slack_report_threads.py
new file mode 100644
index 000000000000..0afe779b95a5
--- /dev/null
+++ b/products/signals/backend/slack_report_threads.py
@@ -0,0 +1,82 @@
+"""The Slack thread ↔ report link behind "reply in the thread and mention PostHog".
+
+Both notification paths (the inbox reviewer notification and the scout harness delivery) record
+the thread they posted, and the Slack mention handler reads it back so the task it starts lands on
+the report's own timeline instead of floating free.
+
+Writes are best-effort: a report must still reach Slack when the link cannot be stored.
+"""
+
+from __future__ import annotations
+
+import logging
+from collections.abc import Sequence
+
+from django.db import IntegrityError
+
+from products.signals.backend.models import SignalReportSlackThread
+
+logger = logging.getLogger(__name__)
+
+
+def record_report_slack_thread(
+ *, team_id: int, report_id: str, integration_id: int | None, slack_workspace_id: str, channel: str, thread_ts: str
+) -> None:
+ """Record that `thread_ts` in `channel` is a notification thread for this report."""
+ try:
+ SignalReportSlackThread.objects.for_team(team_id).get_or_create(
+ slack_workspace_id=slack_workspace_id,
+ channel=channel,
+ thread_ts=thread_ts,
+ defaults={"team_id": team_id, "report_id": report_id, "integration_id": integration_id},
+ )
+ except IntegrityError:
+ # The thread is already claimed — by a concurrent delivery of the same message, or by
+ # another project connected to the same workspace. Either way the first claim stands.
+ pass
+ except Exception:
+ logger.exception(
+ "Failed to record the Slack thread for signal report %s",
+ report_id,
+ extra={"team_id": team_id, "report_id": report_id},
+ )
+
+
+def report_id_for_slack_thread(*, team_id: int, slack_workspace_id: str, channel: str, thread_ts: str) -> str | None:
+ """The report a Slack thread is about, or None when the thread is not a notification thread.
+
+ Scoped to `team_id` rather than to the integration that posted: a workspace can be connected to
+ several projects, and a mention routed to a different project must not reach this project's
+ report. Reconnecting the workspace writes a new integration row, so keying on it instead would
+ lose every link the old row had made.
+ """
+ try:
+ row = (
+ SignalReportSlackThread.objects.for_team(team_id)
+ .filter(slack_workspace_id=slack_workspace_id, channel=channel, thread_ts=thread_ts)
+ .values_list("report_id", flat=True)
+ .first()
+ )
+ except Exception:
+ logger.exception(
+ "Failed to resolve the signal report for a Slack thread", extra={"team_id": team_id, "channel": channel}
+ )
+ return None
+ return str(row) if row else None
+
+
+def report_team_id_for_slack_thread(
+ *, team_ids: Sequence[int], slack_workspace_id: str, channel: str, thread_ts: str
+) -> int | None:
+ """Find the report's environment among the caller's accessible Slack integration candidates."""
+ try:
+ return (
+ SignalReportSlackThread.all_teams.filter(
+ team_id__in=team_ids, slack_workspace_id=slack_workspace_id, channel=channel, thread_ts=thread_ts
+ )
+ .values_list("team_id", flat=True)
+ .first()
+ )
+ except Exception:
+ logger.exception("Failed to resolve the environment for a Slack report thread", extra={"channel": channel})
+ return None
diff --git a/products/signals/backend/test/test_feedback_scout_notes.py b/products/signals/backend/test/test_feedback_scout_notes.py
index 05d5d2623015..3a305f900635 100644
--- a/products/signals/backend/test/test_feedback_scout_notes.py
+++ b/products/signals/backend/test/test_feedback_scout_notes.py
@@ -164,7 +164,7 @@ class TestFeedbackScoutNotes(APIBaseTest):
assert body["forwarded"] is False
assert self._notes() == []
- action = SignalReportAction.objects.get(report=report, user=self.user)
+ action = SignalReportAction.objects.for_team(self.team.id).get(report=report, user=self.user)
assert action.type == SignalReportAction.ActionType.FEEDBACK
assert action.metadata == {"sentiment": "positive"}
@@ -176,7 +176,7 @@ class TestFeedbackScoutNotes(APIBaseTest):
self._feedback(report, sentiment="positive")
self._feedback(report, sentiment="negative")
- action = SignalReportAction.objects.get(report=report, user=self.user)
+ action = SignalReportAction.objects.for_team(self.team.id).get(report=report, user=self.user)
assert action.count == 2
assert action.metadata == {"sentiment": "negative"}
@@ -190,7 +190,7 @@ class TestFeedbackScoutNotes(APIBaseTest):
self._feedback(report, sentiment="positive")
self._feedback(report, sentiment="positive", note="the staging spike is a known issue")
- action = SignalReportAction.objects.get(report=report, user=self.user)
+ action = SignalReportAction.objects.for_team(self.team.id).get(report=report, user=self.user)
assert action.count == 1
assert action.metadata == {"sentiment": "positive"}
assert len(self._notes()) == 1
@@ -202,7 +202,7 @@ class TestFeedbackScoutNotes(APIBaseTest):
self._feedback(report, sentiment="negative", note="not useful")
- action = SignalReportAction.objects.get(report=report, user=self.user)
+ action = SignalReportAction.objects.for_team(self.team.id).get(report=report, user=self.user)
assert action.count == 1
assert action.metadata == {"sentiment": "negative"}
diff --git a/products/signals/backend/test/test_scout_inactivity.py b/products/signals/backend/test/test_scout_inactivity.py
index 5b270bab6fd9..758837431590 100644
--- a/products/signals/backend/test/test_scout_inactivity.py
+++ b/products/signals/backend/test/test_scout_inactivity.py
@@ -204,6 +204,7 @@ class TestScoutInactivitySweep(BaseTest):
# wanted, even when they never resolve or dismiss it.
("view_action", None, None, SignalReportAction.ActionType.VIEW),
("feedback_action", None, None, SignalReportAction.ActionType.FEEDBACK),
+ ("slack_discussion", None, None, SignalReportAction.ActionType.SLACK_DISCUSSION),
]
)
def test_engagement_with_a_report_keeps_a_scout_running(
diff --git a/products/signals/backend/test/test_scout_slack_delivery.py b/products/signals/backend/test/test_scout_slack_delivery.py
index 5650da72d300..37999f6cd135 100644
--- a/products/signals/backend/test/test_scout_slack_delivery.py
+++ b/products/signals/backend/test/test_scout_slack_delivery.py
@@ -30,6 +30,7 @@ from products.signals.backend.scout_harness.slack_delivery import (
post_scout_emission_to_slack,
)
from products.signals.backend.scout_harness.slack_delivery_queue import queue_configured_scout_slack_delivery
+from products.signals.backend.slack_report_threads import report_id_for_slack_thread
from products.signals.backend.tasks import (
deliver_scout_slack_output,
deliver_scout_slack_thread_replies,
@@ -161,7 +162,17 @@ class TestScoutSlackDelivery(BaseTest):
assert fake_client.chat_postMessage.call_count == 1
assert call["blocks"][-1]["type"] == "actions"
- def test_posts_report_with_safe_markdown_and_delivery_id(self) -> None:
+ @parameterized.expand(
+ [
+ ("channel", "CSCOUTS|#scout-findings", "CSCOUTS", "CSCOUTS"),
+ # Posting to a member id opens a direct message, so Slack answers with the `D…`
+ # conversation. An inbound mention names that conversation, not the member id.
+ ("direct_message", "U123ABC45|@andy", "U123ABC45", "D123ABC45"),
+ ]
+ )
+ def test_posts_report_with_safe_markdown_and_delivery_id(
+ self, _name, channel_config, sent_channel, posted_channel
+ ) -> None:
emission = self._make_emission()
report = SignalReport.objects.create(
team=self.team,
@@ -174,9 +185,11 @@ class TestScoutSlackDelivery(BaseTest):
"| [#93147 fix(checkout): retry 500s](https://example.com/pull/93147) | ready |\n"
),
)
- integration = Integration.objects.create(team=self.team, kind=Integration.IntegrationKind.SLACK)
+ integration = Integration.objects.create(
+ team=self.team, kind=Integration.IntegrationKind.SLACK, integration_id="T_SCOUTS"
+ )
fake_client = MagicMock()
- fake_client.chat_postMessage.return_value = {"ts": "1785418710.000200"}
+ fake_client.chat_postMessage.return_value = {"ts": "1785418710.000200", "channel": posted_channel}
delivery_id = "01864f4c-6957-7d3f-8d85-1d775e527265"
with patch("products.signals.backend.scout_harness.slack_delivery.SlackIntegration") as slack_integration:
@@ -188,11 +201,11 @@ class TestScoutSlackDelivery(BaseTest):
str(emission.scout_run_id),
delivery_id,
integration.id,
- "CSCOUTS|#scout-findings",
+ channel_config,
)
call = fake_client.chat_postMessage.call_args_list[0].kwargs
- assert call["channel"] == "CSCOUTS"
+ assert call["channel"] == sent_channel
assert call["client_msg_id"] == delivery_id
assert "thread_ts" not in call
markdown = call["blocks"][2]["text"]
@@ -210,6 +223,12 @@ class TestScoutSlackDelivery(BaseTest):
)
assert call["blocks"][-1]["type"] == "context"
assert fake_client.chat_postMessage.call_count == 1
+ assert report_id_for_slack_thread(
+ slack_workspace_id=integration.integration_id,
+ team_id=self.team.id,
+ channel=posted_channel,
+ thread_ts="1785418710.000200",
+ ) == str(report.id)
def test_note_only_edit_delivers_the_note_instead_of_the_report(self) -> None:
# Without the edit_note branch a note-only edit re-posts the full report message, which is
diff --git a/products/signals/backend/test/test_signal_report_actions.py b/products/signals/backend/test/test_signal_report_actions.py
index 991307d6c233..d51526525f3c 100644
--- a/products/signals/backend/test/test_signal_report_actions.py
+++ b/products/signals/backend/test/test_signal_report_actions.py
@@ -1,6 +1,8 @@
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
+from django.utils import timezone
+
from parameterized import parameterized
from rest_framework import status
@@ -23,19 +25,40 @@ class TestSignalReportViewedEndpoint(APIBaseTest):
**overrides,
)
- def test_a_view_is_recorded_once_per_person_and_repeats_bump_the_row(self) -> None:
+ @parameterized.expand(
+ [("project", False, False), ("child_environment", True, False), ("existing_child_action", True, True)]
+ )
+ def test_a_view_is_recorded_once_per_person_and_repeats_bump_the_row(
+ self, _name, child_environment, existing_action
+ ) -> None:
+ action_team_id = self.team.id
+ if child_environment:
+ from posthog.models.team.team import Team
+
+ self.team = Team.objects.create(
+ organization=self.organization, parent_team=self.team, name="Child environment"
+ )
report = self._create_report()
+ if existing_action:
+ SignalReportAction.all_teams.create(
+ team_id=action_team_id,
+ report=report,
+ user=self.user,
+ type=SignalReportAction.ActionType.VIEW,
+ last_at=timezone.now(),
+ )
first = self.client.post(self._viewed_url(str(report.pk)))
assert first.status_code == status.HTTP_204_NO_CONTENT
- action = SignalReportAction.objects.get(report=report, user=self.user)
+ action = SignalReportAction.objects.for_team(self.team.id).get(report=report, user=self.user)
+ assert action.team_id == action_team_id
assert action.type == SignalReportAction.ActionType.VIEW
- assert action.count == 1
+ assert action.count == 1 + int(existing_action)
first_seen = action.last_at
assert self.client.post(self._viewed_url(str(report.pk))).status_code == status.HTTP_204_NO_CONTENT
action.refresh_from_db()
- assert action.count == 2
+ assert action.count == 2 + int(existing_action)
assert action.last_at > first_seen
@parameterized.expand(
@@ -65,7 +88,7 @@ class TestSignalReportViewedEndpoint(APIBaseTest):
)
assert response.status_code == expected_status
- assert not SignalReportAction.objects.filter(report=report).exists()
+ assert not SignalReportAction.objects.for_team(self.team.id).filter(report=report).exists()
@parameterized.expand(
[
@@ -89,7 +112,7 @@ class TestSignalReportViewedEndpoint(APIBaseTest):
)
assert response.status_code == expected_status
- assert not SignalReportAction.objects.filter(report=report).exists()
+ assert not SignalReportAction.objects.for_team(self.team.id).filter(report=report).exists()
def test_a_suppressed_report_still_records_its_view(self) -> None:
# The Dismissed tab renders the same detail view, so its opens must count too instead of
@@ -99,4 +122,4 @@ class TestSignalReportViewedEndpoint(APIBaseTest):
response = self.client.post(self._viewed_url(str(report.pk)))
assert response.status_code == status.HTTP_204_NO_CONTENT
- assert SignalReportAction.objects.filter(report=report, user=self.user).exists()
+ assert SignalReportAction.objects.for_team(self.team.id).filter(report=report, user=self.user).exists()
diff --git a/products/signals/backend/test/test_slack_inbox_notifications.py b/products/signals/backend/test/test_slack_inbox_notifications.py
index 756c103655a7..edfd4179a16b 100644
--- a/products/signals/backend/test/test_slack_inbox_notifications.py
+++ b/products/signals/backend/test/test_slack_inbox_notifications.py
@@ -33,6 +33,7 @@ from products.signals.backend.slack_inbox_notifications import (
dispatch_inbox_item_notifications,
dispatch_reviewer_added_notifications,
)
+from products.signals.backend.slack_report_threads import report_id_for_slack_thread
from products.signals.backend.tasks import send_reviewer_added_slack_notifications
@@ -410,6 +411,44 @@ def test_dispatch_posts_to_team_channel_without_per_user_config(org_and_team, ai
assert ("@PostHog" in call_kwargs["blocks"][-1]["elements"][0]["text"]) is ai_approved
+ ("target", "posted_channel"),
+ [
+ ("C123|#inbox", "C123"),
+ # Posting to a member id opens a direct message, so Slack answers with the `D…`
+ # conversation. An inbound mention names that conversation, not the member id.
+ ("U0123ABC456|@reviewer", "D0123ABC456"),
+ ],
+)
+def test_dispatch_records_the_notification_thread_for_the_report(org_and_team, target, posted_channel):
+ # The message invites a reply mentioning PostHog, which starts a task. Dropping the posted
+ # `ts`, or storing the id we sent instead of the one Slack answered with, leaves that task
+ # with no way back to the report it discusses.
+ org, team = org_and_team
+ reviewer = _make_reviewer_user(org, "[email protected]", "thread-bot")
+ integration = _make_slack_integration(team, reviewer)
+ SignalUserAutonomyConfig.objects.create(
+ user=reviewer,
+ slack_notification_integration=integration,
+ slack_notification_channel=target,
+ )
+ report = _make_ready_report(team, priority=AutonomyPriority.P1, suggested_logins=["thread-bot"])
+
+ fake_client = MagicMock()
+ fake_client.chat_postMessage.return_value = {"ok": True, "ts": "1700000000.000100", "channel": posted_channel}
+ with patch("products.signals.backend.slack_inbox_notifications.SlackIntegration") as slack_cls:
+ slack_cls.return_value.client = fake_client
+ dispatch_inbox_item_notifications(str(report.id), team.id)
+
+ assert report_id_for_slack_thread(
+ slack_workspace_id=integration.integration_id,
+ team_id=team.id,
+ channel=posted_channel,
+ thread_ts="1700000000.000100",
+ ) == str(report.id)
+
+
@pytest.mark.django_db
def test_dispatch_falls_back_to_team_channel_without_suggested_reviewers(org_and_team):
org, team = org_and_team
diff --git a/products/signals/backend/test/test_slack_report_threads.py b/products/signals/backend/test/test_slack_report_threads.py
new file mode 100644
index 000000000000..e9f919a3512b
--- /dev/null
+++ b/products/signals/backend/test/test_slack_report_threads.py
@@ -0,0 +1,123 @@
+import pytest
+
+from posthog.models import Organization, Team
+from posthog.models.integration import Integration
+
+from products.signals.backend.models import SignalReport, SignalReportSlackThread
+from products.signals.backend.slack_report_threads import record_report_slack_thread, report_id_for_slack_thread
+
+
+def team():
+ org = Organization.objects.create(name="slack-thread-org")
+ team = Team.objects.create(organization=org, name="slack-thread-team")
+ yield team
+ team.delete()
+ org.delete()
+
+
+def _integration(team: Team) -> Integration:
+ return Integration.objects.create(
+ team=team,
+ kind="slack",
+ integration_id="T123",
+ config={"team": {"id": "T123"}},
+ sensitive_config={"access_token": "xoxb-test"},
+ )
+
+
+def _report(team: Team) -> SignalReport:
+ return SignalReport.objects.create(
+ team=team, status=SignalReport.Status.READY, title="A report", summary="Summary", total_weight=1.0
+ )
+
+
+ ("channel", "thread_ts", "resolves"),
+ [
+ ("CTEAM", "1700000000.000100", True),
+ # A mention in a different thread of the same channel is an ordinary Slack conversation.
+ ("CTEAM", "1700000000.000200", False),
+ ("COTHER", "1700000000.000100", False),
+ ],
+)
+def test_only_the_recorded_thread_resolves_to_the_report(team, channel, thread_ts, resolves):
+ report = _report(team)
+ record_report_slack_thread(
+ slack_workspace_id="T123",
+ team_id=team.id,
+ report_id=str(report.id),
+ integration_id=_integration(team).id,
+ channel="CTEAM",
+ thread_ts="1700000000.000100",
+ )
+
+ resolved = report_id_for_slack_thread(
+ slack_workspace_id="T123", team_id=team.id, channel=channel, thread_ts=thread_ts
+ )
+
+ assert resolved == (str(report.id) if resolves else None)
+
+
[email protected]("boundary", ["organization", "parent", "sibling"])
+def test_thread_recorded_for_another_teams_report_does_not_resolve(team, boundary):
+ if boundary == "organization":
+ other_org = Organization.objects.create(name="slack-thread-other-org")
+ other_team = Team.objects.create(organization=other_org, name="slack-thread-other-team")
+ lookup_team = team
+ else:
+ other_team = Team.objects.create(organization=team.organization, name="Report environment", parent_team=team)
+ lookup_team = (
+ team
+ if boundary == "parent"
+ else Team.objects.create(organization=team.organization, name="Other environment", parent_team=team)
+ )
+ report = _report(other_team)
+ record_report_slack_thread(
+ slack_workspace_id="T123",
+ team_id=other_team.id,
+ report_id=str(report.id),
+ integration_id=_integration(other_team).id,
+ channel="CTEAM",
+ thread_ts="1700000000.000100",
+ )
+
+ assert report_id_for_slack_thread(
+ slack_workspace_id="T123", team_id=other_team.id, channel="CTEAM", thread_ts="1700000000.000100"
+ ) == str(report.id)
+ assert (
+ report_id_for_slack_thread(
+ slack_workspace_id="T123", team_id=lookup_team.id, channel="CTEAM", thread_ts="1700000000.000100"
+ )
+ is None
+ )
+
+
[email protected]("second_workspace", ["T123", "TOTHER"])
+def test_re_recording_the_same_thread_keeps_the_first_report(team, second_workspace):
+ # Two deliveries racing on one message, and an edit redelivery, both land here. The thread
+ # itself is unchanged, so the second write must not fork the link or raise.
+ first, second = _report(team), _report(team)
+ integration = _integration(team)
+ for report, workspace in ((first, "T123"), (second, second_workspace)):
+ record_report_slack_thread(
+ slack_workspace_id=workspace,
+ team_id=team.id,
+ report_id=str(report.id),
+ integration_id=integration.id,
+ channel="CTEAM",
+ thread_ts="1700000000.000100",
+ )
+
+ assert SignalReportSlackThread.objects.for_team(team.id).count() == (1 if second_workspace == "T123" else 2)
+ assert report_id_for_slack_thread(
+ slack_workspace_id="T123", team_id=team.id, channel="CTEAM", thread_ts="1700000000.000100"
+ ) == str(first.id)
+
+ if second_workspace != "T123":
+ assert report_id_for_slack_thread(
+ slack_workspace_id=second_workspace, team_id=team.id, channel="CTEAM", thread_ts="1700000000.000100"
+ ) == str(second.id)
diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.py
index c39d438a025e..546189aa69d5 100644
--- a/products/slack_app/backend/api.py
+++ b/products/slack_app/backend/api.py
@@ -735,20 +735,24 @@ def _workspace_claims_cache_key(slack_team_id: str, kinds: list[str]) -> str:
return f"slack_app:ws_claims:{slack_team_id}:{kinds_token}"
-def does_other_region_claim_workspace(*, slack_team_id: str, kinds: list[str], incoming_host: str) -> bool | None:
+def does_other_region_claim_workspace(
+ *,
+ slack_team_id: str,
+ kinds: list[str],
+ incoming_host: str,
+ channel: str | None = None,
+ thread_ts: str | None = None,
+) -> bool | None:
"""Ask the other region whether it claims the given workspace for any of the kinds.
- Ownership is asked at workspace granularity on purpose. Project ids are issued per region, so
- "does the other region hold project 2 for this workspace" compares two unrelated numbering
- spaces and answers no almost every time — which reads as "we own this" and pins the event to
- whichever region Slack happened to deliver it to.
-
- Returns True/False on a definitive answer, or None on transport failure or bad response.
- Definitive answers are cached for ``WORKSPACE_CLAIMS_CACHE_TTL_SECONDS`` so a single probe
- flake does not reroute the next event. None is never cached so the next event re-probes.
+ Project IDs differ between regions, so probes use Slack workspace and thread IDs.
+ Thread probes bypass the workspace cache because a notification can create a new mapping.
+ Returns None when the peer cannot confirm ownership. Workspace-only probes cache definitive
+ answers for ``WORKSPACE_CLAIMS_CACHE_TTL_SECONDS``.
"""
cache_key = _workspace_claims_cache_key(slack_team_id, kinds)
- cached = cache.get(cache_key)
+ thread_probe = bool(channel and thread_ts)
+ cached = None if thread_probe else cache.get(cache_key)
if isinstance(cached, bool):
logger.info(
"slack_app_workspace_claims_cache_hit",
@@ -761,7 +765,10 @@ def does_other_region_claim_workspace(*, slack_team_id: str, kinds: list[str], i
scheme = "http" if settings.DEBUG else "https"
target_url = f"{scheme}://{target_domain}/slack/workspace/claims/"
- body = json.dumps({"slack_team_id": slack_team_id, "kinds": kinds}).encode("utf-8")
+ payload: dict[str, Any] = {"slack_team_id": slack_team_id, "kinds": kinds}
+ if thread_probe:
+ payload.update(channel=channel, thread_ts=thread_ts)
+ body = json.dumps(payload).encode("utf-8")
signing_secret = SlackIntegration.slack_config()["SLACK_APP_SIGNING_SECRET"]
signed = sign_slack_request(body, signing_secret)
@@ -795,12 +802,13 @@ def does_other_region_claim_workspace(*, slack_team_id: str, kinds: list[str], i
logger.warning("slack_app_workspace_claims_bad_json", target_url=target_url)
return None
- claimed = data.get("claimed")
+ claimed = data.get("thread_claimed" if thread_probe else "claimed")
if not isinstance(claimed, bool):
logger.warning("slack_app_workspace_claims_bad_payload", target_url=target_url)
return None
- cache.set(cache_key, claimed, timeout=WORKSPACE_CLAIMS_CACHE_TTL_SECONDS)
+ if not thread_probe:
+ cache.set(cache_key, claimed, timeout=WORKSPACE_CLAIMS_CACHE_TTL_SECONDS)
return claimed
@@ -845,6 +853,13 @@ def slack_workspace_claims_view(request: HttpRequest) -> HttpResponse:
kind__in=filtered,
integration_id=slack_team_id,
).exists()
+ channel, thread_ts = data.get("channel"), data.get("thread_ts")
+ if channel is not None or thread_ts is not None:
+ if not isinstance(channel, str) or not channel or not isinstance(thread_ts, str) or not thread_ts:
+ return HttpResponse("Invalid thread", status=400)
+ candidates = list(Integration.objects.filter(kind__in=filtered, integration_id=slack_team_id))
+ result = resolve_from_candidates(candidates, slack_team_id=slack_team_id, channel=channel, thread_ts=thread_ts)
+ return JsonResponse({"claimed": claimed, "thread_claimed": result.source == "thread"})
return JsonResponse({"claimed": claimed})
@@ -1943,6 +1958,9 @@ def _route_assistant_event(
other_domain=other_domain,
incoming_host=incoming_host,
can_defer=can_defer,
+ channel=fields.dm_channel_id,
+ thread_ts=fields.thread_ts if event.get("thread_ts") else None,
+ local_thread=result.source == "thread",
)
if region_route is not None:
return region_route
@@ -2306,6 +2324,9 @@ def route_posthog_code_event_to_relevant_region(
other_domain=other_domain,
incoming_host=incoming_host,
can_defer=can_defer_to_other_region,
+ channel=channel_str,
+ thread_ts=thread_ts_str if mention_is_threaded else None,
+ local_thread=workspace_result.source == "thread",
)
if region_route is not None:
# A mention that no region claims is the most confusing failure of all: the
@@ -2689,6 +2710,9 @@ def resolve_region_or_terminal_route(
other_domain: str,
incoming_host: str,
can_defer: bool,
+ channel: str | None = None,
+ thread_ts: str | None = None,
+ local_thread: bool = False,
) -> str | None:
"""Shared region gate for every coding-agent surface (mentions, channel followups, DMs).
@@ -2696,6 +2720,21 @@ def resolve_region_or_terminal_route(
local integration claims the workspace, or proxied to US under the US-precedence rule — else
``None`` to signal the caller should keep handling the event locally.
"""
+ if local_thread:
+ return None
+ if channel and thread_ts and not proxied and cross_region_routing_enabled():
+ thread_claimed = does_other_region_claim_workspace(
+ slack_team_id=slack_team_id,
+ kinds=kinds,
+ incoming_host=incoming_host,
+ channel=channel,
+ thread_ts=thread_ts,
+ )
+ if thread_claimed is True:
+ return _proxy_event_and_return_route(request, other_domain)
+ if thread_claimed is None:
+ # Unknown ownership must not send report context to an unrelated project.
+ return ROUTE_PROXY_FAILED
if not candidates_present:
return _route_to_other_region_or_drop(request, slack_team_id, proxied=proxied, other_domain=other_domain)
if _us_should_handle_instead(slack_team_id, kinds, can_defer, incoming_host):
diff --git a/products/slack_app/backend/services/integration_resolver.py b/products/slack_app/backend/services/integration_resolver.py
index 7c764afb0dd7..666b7397f041 100644
--- a/products/slack_app/backend/services/integration_resolver.py
+++ b/products/slack_app/backend/services/integration_resolver.py
@@ -12,8 +12,10 @@ from posthog.models.integration import Integration
from posthog.models.user import User
from posthog.user_permissions import UserPermissions
+from products.signals.backend.facade import api as signals_facade
from products.slack_app.backend.helpers import local_dev_slack_email
from products.slack_app.backend.models import SlackSettings, SlackThreadTaskMapping
+from products.slack_app.backend.services.slack_fork_context import get_pending_fork
from products.slack_app.backend.services.slack_scopes import bot_is_ready
logger = structlog.get_logger(__name__)
@@ -194,6 +196,21 @@ def resolve_from_candidates(
if target is not None and (accessible_team_ids is None or target.team_id in accessible_team_ids):
return ResolutionResult(integration=target, source="thread", candidates=accessible)
+ for candidate in accessible:
+ if get_pending_fork(candidate.id, channel, thread_ts) is not None:
+ return ResolutionResult(integration=candidate, source="thread", candidates=accessible)
+
+ report_team_id = signals_facade.report_team_id_for_slack_thread(
+ team_ids=[candidate.team_id for candidate in accessible],
+ slack_workspace_id=slack_team_id,
+ channel=channel,
+ thread_ts=thread_ts,
+ )
+ if report_team_id is not None:
+ return ResolutionResult(
+ integration=candidates_by_team_id[report_team_id], source="thread", candidates=accessible
+ )
+
if slack_user_id:
# One query returns at most two rows: the per-user row and the
# workspace-wide row. Sorting with NULL-last puts the per-user row first.
diff --git a/products/slack_app/backend/tests/test_followup_forwarding.py b/products/slack_app/backend/tests/test_followup_forwarding.py
index 4c01e7a16071..20d497ded6b6 100644
--- a/products/slack_app/backend/tests/test_followup_forwarding.py
+++ b/products/slack_app/backend/tests/test_followup_forwarding.py
@@ -254,6 +254,90 @@ class TestCreatePostHogCodeTaskForRepoActivity(TestCase):
assert mapping.task_id == task.id
assert mapping.task_run_id == task.latest_run.id
+ @parameterized.expand(
+ [
+ ("report_notification_thread", True, None),
+ ("mapping_failure", True, "mapping"),
+ ("association_failure", True, "association"),
+ ("ordinary_thread", False, None),
+ ]
+ )
+ @patch("products.tasks.backend.facade.temporal.dispatch_task_processing_workflow")
+ @patch("posthog.models.integration.SlackIntegration")
+ def test_task_from_a_report_notification_thread_lands_on_the_report(
+ self, _name, from_report_thread, failure_stage, mock_slack_cls, _mock_execute_workflow
+ ):
+ from products.signals.backend.models import SignalReport, SignalReportAction, SignalReportArtefact
+ from products.signals.backend.slack_report_threads import record_report_slack_thread
+
+ mock_slack_instance = MagicMock()
+ mock_slack_instance.client.chat_getPermalink.return_value = {
+ "ok": True,
+ "permalink": "https://slack.example.com/thread",
+ }
+ mock_slack_cls.return_value = mock_slack_instance
+ report = SignalReport.objects.create(
+ team=self.team, status=SignalReport.Status.READY, title="R", summary="S", total_weight=1.0
+ )
+ if from_report_thread:
+ record_report_slack_thread(
+ slack_workspace_id=self.integration.integration_id,
+ team_id=self.team.id,
+ report_id=str(report.id),
+ integration_id=self.integration.id,
+ channel="C123",
+ thread_ts="1234.5678",
+ )
+
+ inputs = _make_inputs(self.integration.id, self.user.id)
+ args = (
+ inputs,
+ "C123",
+ "1234.5678",
+ "U_ALICE",
+ self.user.id,
+ inputs.event,
+ [SlackThreadMessage(user="U_ALICE", text="look into this")],
+ None,
+ )
+ if failure_stage:
+ failure_target = (
+ patch.object(
+ SlackThreadTaskMapping.objects, "update_or_create", side_effect=RuntimeError("mapping unavailable")
+ )
+ if failure_stage == "mapping"
+ else patch.object(SignalReportAction, "record", side_effect=RuntimeError("action unavailable"))
+ )
+ with failure_target:
+ with self.assertRaises(RuntimeError):
+ create_posthog_code_task_for_repo_activity(*args)
+ orphan = self.Task.objects.get(team=self.team)
+ assert orphan.signal_report_id is None
+ assert not SignalReportArtefact.objects.filter(report_id=report.id).exists()
+ create_posthog_code_task_for_repo_activity(*args)
+ create_posthog_code_task_for_repo_activity(*args)
+
+ mapping = SlackThreadTaskMapping.objects.get(
+ integration=self.integration, channel="C123", thread_ts="1234.5678"
+ )
+ task = mapping.task
+ assert task.origin_product == self.Task.OriginProduct.SLACK
+ assert task.signal_report_id == (report.id if from_report_thread else None)
+ work_log = SignalReportArtefact.objects.filter(
+ report_id=report.id, type=SignalReportArtefact.ArtefactType.TASK_RUN, task_id=task.id
+ )
+ assert work_log.count() == int(from_report_thread)
+ from products.signals.backend.scout_harness.inactivity import _engaged_report_ids
+
+ assert (
+ str(report.id) in _engaged_report_ids(self.team.id, {str(report.id)}, report.created_at)
+ ) is from_report_thread
+ if from_report_thread:
+ action = SignalReportAction.objects.for_team(self.team.id).get(report_id=report.id)
+ assert action.user_id == self.user.id
+ assert action.count == 1
+ assert work_log.get().created_by_id is None
+
@patch("products.tasks.backend.facade.temporal.dispatch_task_processing_workflow")
@patch("posthog.models.integration.SlackIntegration")
def test_initial_task_uploads_slack_attachment_to_pending_prompt(
diff --git a/products/slack_app/backend/tests/test_fork_thread.py b/products/slack_app/backend/tests/test_fork_thread.py
index 9e8219008efb..40ad6990881d 100644
--- a/products/slack_app/backend/tests/test_fork_thread.py
+++ b/products/slack_app/backend/tests/test_fork_thread.py
@@ -331,22 +331,34 @@ class TestPendingForkHandoff(TestCase):
)
def _reply_in_dm(self):
- from products.slack_app.backend.api import _handle_assistant_dm_message
+ from django.test import RequestFactory
- event = {"type": "message", "channel": "D_ALICE", "ts": "999.2", "thread_ts": "999.1", "user": "U_ALICE"}
+ from products.slack_app.backend.api import route_posthog_code_event_to_relevant_region
+ from products.slack_app.backend.models import SlackSettings
+
+ other_team = Team.objects.create(organization=self.org, name="Default project")
+ other = Integration.objects.create(team=other_team, kind="slack", integration_id="T_SLACK")
+ SlackSettings.objects.update_or_create(
+ slack_workspace_id="T_SLACK", slack_user_id="U_ALICE", defaults={"default_integration": other}
+ )
+ event = {
+ "type": "message",
+ "channel_type": "im",
+ "text": "Please explain",
+ "channel": "D_ALICE",
+ "ts": "999.2",
+ "thread_ts": "999.1",
+ "user": "U_ALICE",
+ }
with (
patch("products.slack_app.backend.api.SlackIntegration") as slack_cls,
patch("products.slack_app.backend.api._start_mention_workflow") as start,
+ patch("products.slack_app.backend.api.resolve_posthog_user_from_event", return_value=self.user),
+ patch("products.slack_app.backend.api.cross_region_routing_enabled", return_value=False),
):
slack_cls.return_value.missing_scopes.return_value = set()
- _handle_assistant_dm_message(
- event,
- self.integration,
- "T_SLACK",
- None,
- "D_ALICE",
- "999.1",
- posthog_user=self.user,
+ route_posthog_code_event_to_relevant_region(
+ RequestFactory().post("/slack/event-callback/"), event, "T_SLACK"
)
return start
@@ -364,6 +376,7 @@ class TestPendingForkHandoff(TestCase):
start = self._reply_in_dm()
+ assert start.call_args.args[1] == self.integration
kwargs = start.call_args.kwargs
assert kwargs["fork_source_channel"] == "C_SOURCE"
assert kwargs["fork_source_thread_ts"] == "111.1"
diff --git a/products/slack_app/backend/tests/test_integration_resolver.py b/products/slack_app/backend/tests/test_integration_resolver.py
index 89160484315e..d5078e6c73c1 100644
--- a/products/slack_app/backend/tests/test_integration_resolver.py
+++ b/products/slack_app/backend/tests/test_integration_resolver.py
@@ -13,6 +13,7 @@ from products.slack_app.backend.models import SlackSettings, SlackThreadTaskMapp
from products.slack_app.backend.services.integration_resolver import (
load_integrations,
pick_a_project_message,
+ resolve_from_candidates,
resolve_user_for_workspace,
)
@@ -82,12 +83,36 @@ class TestResolveIntegration:
integration: Integration,
channel: str = "C1",
thread_ts: str = "123.456",
- ) -> SlackThreadTaskMapping:
+ mapping_kind: str = "task",
+ ) -> None:
+ if mapping_kind == "fork":
+ from products.slack_app.backend.services.slack_fork_context import PendingFork, store_pending_fork
+
+ store_pending_fork(
+ integration.id,
+ channel,
+ thread_ts,
+ PendingFork(source_channel="CSOURCE", source_thread_ts="100.1", is_ext_shared=True),
+ )
+ return
+ if mapping_kind == "report":
+ SignalReport = apps.get_model("signals", "SignalReport")
+ SignalReportSlackThread = apps.get_model("signals", "SignalReportSlackThread")
+ report = SignalReport.objects.create(team=team, title="Report", summary="Summary")
+ SignalReportSlackThread.objects.for_team(team.id).create(
+ team=team,
+ report=report,
+ integration=integration,
+ slack_workspace_id=integration.integration_id,
+ channel=channel,
+ thread_ts=thread_ts,
+ )
+ return
Task = apps.get_model("tasks", "Task")
TaskRun = apps.get_model("tasks", "TaskRun")
task = Task.objects.create(team=team, title="t")
task_run = TaskRun.objects.create(team=team, task=task)
- return SlackThreadTaskMapping.objects.create(
+ SlackThreadTaskMapping.objects.create(
team=team,
integration=integration,
slack_workspace_id=WORKSPACE,
@@ -98,14 +123,16 @@ class TestResolveIntegration:
mentioning_slack_user_id=SLACK_USER,
)
- def test_thread_mapping_wins_over_everything(self):
- self._mk_thread_mapping(team=self.team_b, integration=self.integration_b)
- # Even with an unrelated user_default pointing at A, the thread mapping wins.
- SlackSettings.objects.create(
- default_integration=self.integration_a,
- slack_workspace_id=WORKSPACE,
- slack_user_id=SLACK_USER,
- )
+ @pytest.mark.parametrize("mapping_kind", ["task", "report", "fork"])
+ @pytest.mark.parametrize("has_default", [False, True])
+ def test_thread_mapping_wins_over_everything(self, mapping_kind, has_default):
+ self._mk_thread_mapping(team=self.team_b, integration=self.integration_b, mapping_kind=mapping_kind)
+ if has_default:
+ SlackSettings.objects.create(
+ default_integration=self.integration_a,
+ slack_workspace_id=WORKSPACE,
+ slack_user_id=SLACK_USER,
+ )
result = load_integrations(
slack_team_id=WORKSPACE,
@@ -119,12 +146,13 @@ class TestResolveIntegration:
assert result.source == "thread"
assert result.integration == self.integration_b
- def test_thread_mapping_ignored_when_user_lacks_access(self):
+ @pytest.mark.parametrize("mapping_kind", ["task", "report", "fork"])
+ def test_thread_mapping_ignored_when_user_lacks_access(self, mapping_kind):
# Thread mapping targets team_c, which the user has no membership in
# (it's in `other_org`). The thread match must be skipped — a user
# whose access was revoked or who never had access can't drive the
# thread just by replying to it.
- self._mk_thread_mapping(team=self.team_c, integration=self.integration_c)
+ self._mk_thread_mapping(team=self.team_c, integration=self.integration_c, mapping_kind=mapping_kind)
result = load_integrations(
slack_team_id=WORKSPACE,
@@ -140,7 +168,8 @@ class TestResolveIntegration:
assert result.source == "needs_picker"
assert {i.id for i in result.candidates} == {self.integration_a.id, self.integration_b.id}
- def test_thread_mapping_remaps_to_sibling_when_mapped_integration_out_of_lookup(self):
+ @pytest.mark.parametrize("mapping_kind", ["task", "report"])
+ def test_thread_mapping_remaps_to_sibling_when_mapped_integration_out_of_lookup(self, mapping_kind):
# Older mapping points at a sibling Integration row of a different kind
# for the same team in this workspace. The resolver must remap to the
# in-set sibling and keep the mapping's task_run linkage rather than
@@ -151,7 +180,7 @@ class TestResolveIntegration:
integration_id=WORKSPACE,
sensitive_config={"access_token": "xoxb-legacy"},
)
- self._mk_thread_mapping(team=self.team_b, integration=legacy_integration)
+ self._mk_thread_mapping(team=self.team_b, integration=legacy_integration, mapping_kind=mapping_kind)
result = load_integrations(
slack_team_id=WORKSPACE,
@@ -165,7 +194,8 @@ class TestResolveIntegration:
assert result.source == "thread"
assert result.integration == self.integration_b
- def test_thread_mapping_falls_through_when_no_sibling_for_team(self):
+ @pytest.mark.parametrize("mapping_kind", ["task", "report", "fork"])
+ def test_thread_mapping_falls_through_when_no_sibling_for_team(self, mapping_kind):
# The mapping points at an Integration whose team has no candidate in
# the current lookup at all (kind drift left no replacement). Without a
# sibling to remap to, the resolver must fall through to the next
@@ -177,7 +207,7 @@ class TestResolveIntegration:
integration_id=WORKSPACE,
sensitive_config={"access_token": "xoxb-legacy"},
)
- self._mk_thread_mapping(team=self.team_b, integration=legacy_integration)
+ self._mk_thread_mapping(team=self.team_b, integration=legacy_integration, mapping_kind=mapping_kind)
result = load_integrations(
slack_team_id=WORKSPACE,
@@ -192,6 +222,23 @@ class TestResolveIntegration:
assert result.source == "sole_candidate"
assert result.integration == self.integration_a
+ def test_report_thread_routes_after_integration_is_reconnected(self):
+ self._mk_thread_mapping(team=self.team_b, integration=self.integration_b, mapping_kind="report")
+ self.integration_b.delete()
+ replacement = self._mk_integration(self.team_b)
+
+ result = resolve_from_candidates(
+ self._workspace_integrations(),
+ slack_team_id=WORKSPACE,
+ slack_user_id=SLACK_USER,
+ user=self.user,
+ channel="C1",
+ thread_ts="123.456",
+ )
+
+ assert result.source == "thread"
+ assert result.integration == replacement
+
def test_user_default_used_when_accessible(self):
SlackSettings.objects.create(
default_integration=self.integration_a,
diff --git a/products/slack_app/backend/tests/test_posthog_code_event_handler.py b/products/slack_app/backend/tests/test_posthog_code_event_handler.py
index e76f9f2f19e0..3045795b6acc 100644
--- a/products/slack_app/backend/tests/test_posthog_code_event_handler.py
+++ b/products/slack_app/backend/tests/test_posthog_code_event_handler.py
@@ -197,6 +197,7 @@ class TestPostHogCodeEventHandler(SimpleTestCase):
class TestRoutePostHogCodeEventToRelevantRegion(TestCase):
def setUp(self):
+ self.enterContext(patch("products.slack_app.backend.api.does_other_region_claim_workspace", return_value=False))
from products.slack_app.backend.services.slack_scopes import REQUIRED_SLACK_SCOPES
cache.clear()
@@ -995,6 +996,39 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):
mock_asyncio_run.assert_not_called()
mock_proxy.assert_not_called()
+ @parameterized.expand(
+ [("local", "eu.posthog.com", True, "handled_locally"), ("remote", "us.posthog.com", False, "proxied")]
+ )
+ @override_settings(DEBUG=False, CLOUD_DEPLOYMENT="US")
+ @patch("products.slack_app.backend.api._start_mention_workflow", return_value="handled_locally")
+ @patch("products.slack_app.backend.api._proxy_event_and_return_route", return_value="proxied")
+ @patch("products.slack_app.backend.api.does_other_region_claim_workspace", return_value=True)
+ def test_report_reply_routes_to_owning_region(self, _name, host, local, expected, probe, proxy, start):
+ from products.signals.backend.models import SignalReport, SignalReportSlackThread
+ from products.slack_app.backend.api import route_posthog_code_event_to_relevant_region
+
+ if local:
+ report = SignalReport.objects.create(team=self.team, title="Report", summary="Summary")
+ SignalReportSlackThread.objects.for_team(self.team.id).create(
+ team=self.team,
+ report=report,
+ integration=self.posthog_code_integration,
+ slack_workspace_id="T12345",
+ channel="C001",
+ thread_ts="1234.1",
+ )
+ event = {**self.event, "thread_ts": "1234.1"}
+ result = route_posthog_code_event_to_relevant_region(
+ self.factory.post("/slack/event-callback/", HTTP_HOST=host), event, "T12345"
+ )
+ assert result == expected
+ assert start.call_count == int(local)
+ assert proxy.call_count == int(not local)
+ if local:
+ probe.assert_not_called()
+ else:
+ assert probe.call_args.kwargs["thread_ts"] == "1234.1"
+
@patch("products.slack_app.backend.api.does_other_region_claim_workspace")
@patch("products.slack_app.backend.api._proxy_event_and_return_route")
@patch("products.slack_app.backend.api.asyncio.run")
@@ -1537,6 +1571,7 @@ class TestAssistantEvents(TestCase):
class TestQueueWorkflowDispatch(TestCase):
def setUp(self):
+ self.enterContext(patch("products.slack_app.backend.api.does_other_region_claim_workspace", return_value=False))
from django.utils import timezone
from products.slack_app.backend.services.slack_scopes import REQUIRED_SLACK_SCOPES
diff --git a/products/slack_app/backend/tests/test_thread_message_routing.py b/products/slack_app/backend/tests/test_thread_message_routing.py
index 74c62d6458ef..88eaa2594496 100644
--- a/products/slack_app/backend/tests/test_thread_message_routing.py
+++ b/products/slack_app/backend/tests/test_thread_message_routing.py
@@ -247,12 +247,8 @@ class TestRouteThreadMessage(TestCase):
mock_start.assert_not_called()
@override_settings(SLACK_WORKFLOW_TRIGGERS_ENABLED=True)
- def test_thread_reply_crosses_once_via_region_gate_not_mirror(self):
- # A thread reply on a workspace held in both regions must cross exactly once. The follow-up
- # pipeline's region gate already forwards it to the region that also claims the workspace, so
- # adding an emit-only mirror would make that region emit the reply twice and trigger a
- # workflow twice. Deliver to EU (can defer) with the other region claiming the workspace.
- from products.slack_app.backend.api import ROUTE_PROXIED, route_posthog_code_event_to_relevant_region
+ def test_owned_thread_stays_local_without_an_emit_only_mirror(self):
+ from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY, route_posthog_code_event_to_relevant_region
event = self._make_event() # thread_ts != ts, a reply
request = self.factory.post("/slack/event-callback/", HTTP_HOST="eu.posthog.com")
@@ -260,13 +256,17 @@ class TestRouteThreadMessage(TestCase):
patch("products.slack_app.backend.api.cross_region_routing_enabled", return_value=True),
patch("products.slack_app.backend.api.does_other_region_claim_workspace", return_value=True),
patch("products.slack_app.backend.api._proxy_event_to_region") as mock_proxy,
+ patch(
+ "products.slack_app.backend.api._start_mention_workflow", return_value=ROUTE_HANDLED_LOCALLY
+ ) as start,
patch("products.slack_app.backend.tasks.mirror_slack_message_event.delay") as mock_delay,
patch("products.slack_app.backend.slack_workflow_events.produce_internal_event"),
):
result = route_posthog_code_event_to_relevant_region(request, event, "T_SLACK")
- assert result == ROUTE_PROXIED
- mock_proxy.assert_called_once()
+ assert result == ROUTE_HANDLED_LOCALLY
+ mock_proxy.assert_not_called()
+ start.assert_called_once()
mock_delay.assert_not_called()
# --- Mapping + FF gate -------------------------------------------------
diff --git a/products/slack_app/backend/tests/test_workspace_claims.py b/products/slack_app/backend/tests/test_workspace_claims.py
index b9c6a45234c1..82e69538dc76 100644
--- a/products/slack_app/backend/tests/test_workspace_claims.py
+++ b/products/slack_app/backend/tests/test_workspace_claims.py
@@ -4,9 +4,10 @@ from typing import Any
from unittest.mock import MagicMock, patch
from django.core.cache import cache
-from django.test import RequestFactory, TestCase, override_settings
+from django.test import RequestFactory, SimpleTestCase, TestCase, override_settings
import requests
+from parameterized import parameterized
from rest_framework.test import APIClient
from posthog.models.integration import Integration, validate_slack_request
@@ -45,6 +46,27 @@ class TestSlackWorkspaceClaimsView(TestCase):
response = self.client.get("/slack/workspace/claims/")
assert response.status_code == 405
+ @parameterized.expand([("owns_thread", "T_PRESENT", True), ("other_workspace", "T_OTHER", False)])
+ @patch("products.slack_app.backend.api.SlackIntegration.slack_config")
+ def test_report_thread_claim_is_workspace_scoped(self, _name, workspace, expected, mock_config):
+ from products.signals.backend.models import SignalReport, SignalReportSlackThread
+
+ mock_config.return_value = {"SLACK_APP_SIGNING_SECRET": self.signing_secret}
+ integration = Integration.objects.create(team=self.team, kind="slack", integration_id="T_PRESENT")
+ Integration.objects.create(team=self.team, kind="slack", integration_id="T_OTHER")
+ report = SignalReport.objects.create(team=self.team, title="Report", summary="Summary")
+ SignalReportSlackThread.objects.for_team(self.team.id).create(
+ team=self.team,
+ report=report,
+ integration=integration,
+ slack_workspace_id="T_PRESENT",
+ channel="C1",
+ thread_ts="123.1",
+ )
+ response = self._post({"slack_team_id": workspace, "kinds": ["slack"], "channel": "C1", "thread_ts": "123.1"})
+ assert response.status_code == 200
+ assert response.json() == {"claimed": True, "thread_claimed": expected}
+
@patch("products.slack_app.backend.api.SlackIntegration.slack_config")
def test_existing_integration_returns_claimed(self, mock_config):
mock_config.return_value = {"SLACK_APP_SIGNING_SECRET": self.signing_secret}
@@ -152,6 +174,17 @@ class TestDoesOtherRegionClaimWorkspace(TestCase):
response.json.return_value = body
return response
+ @parameterized.expand(
+ [
+ ("thread", {"claimed": True, "thread_claimed": True}, True),
+ ("workspace_only", {"claimed": True, "thread_claimed": False}, False),
+ ("old_peer", {"claimed": True}, None),
+ ]
+ )
+ def test_thread_probe_does_not_use_workspace_claims(self, _name, response, expected):
+ assert self._call(self._response(200, {"claimed": True})) is True
+ assert self._call(self._response(200, response), channel="C1", thread_ts="123.1") is expected
+
def test_returns_true_when_other_region_claims(self):
result = self._call(self._response(200, {"claimed": True}))
assert result is True
@@ -293,3 +326,41 @@ class TestDoesOtherRegionClaimWorkspace(TestCase):
# Loop header is included so even if the endpoint URL were ever swapped to the event
# callback by mistake, the receiver would not re-enter the cross-region machinery.
assert sent_headers["X-PostHog-Region-Proxied"] == "1"
+
+
+@override_settings(CLOUD_DEPLOYMENT="EU", DEBUG=False)
+class TestThreadRegionRouting(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("local_report", "eu.posthog.com", True, True, None),
+ ("remote_report_from_us", "us.posthog.com", False, True, "proxied"),
+ ("remote_report_from_eu", "eu.posthog.com", False, True, "proxied"),
+ ("unknown_owner", "us.posthog.com", False, None, "proxy_failed"),
+ ("no_report", "us.posthog.com", False, False, None),
+ ]
+ )
+ @patch("products.slack_app.backend.api._proxy_event_and_return_route", return_value="proxied")
+ @patch("products.slack_app.backend.api.does_other_region_claim_workspace")
+ def test_thread_owner_precedes_workspace_region(
+ self, _name, host, local_thread, remote_thread, expected, probe, proxy
+ ):
+ from products.slack_app.backend.api import resolve_region_or_terminal_route
+
+ probe.return_value = remote_thread
+ result = resolve_region_or_terminal_route(
+ RequestFactory().post("/slack/events/"),
+ "T_PRESENT",
+ candidates_present=True,
+ kinds=["slack"],
+ proxied=False,
+ incoming_host=host,
+ other_domain="peer.posthog.com",
+ can_defer=host == "eu.posthog.com",
+ channel="C1",
+ thread_ts="123.1",
+ local_thread=local_thread,
+ )
+ assert result == expected
+ assert proxy.call_count == int(expected == "proxied")
+ if local_thread:
+ probe.assert_not_called()
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 7b58f1f3a7bb..21d1f859734f 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -1615,6 +1615,21 @@ def collect_task_run_state_metrics(
# --- Writes ---
+def link_slack_task_to_report(*, team_id: int, task_id: str, report_id: str, user_id: int) -> None:
+ """Link only a saved Slack task; a repeated activity must not add another discussion entry."""
+ from products.signals.backend.facade.api import record_slack_report_discussion
+
+ with transaction.atomic():
+ task = Task.objects.select_for_update().get(
+ team_id=team_id, id=task_id, origin_product=Task.OriginProduct.SLACK, created_by_id=user_id
+ )
+ if task.signal_report_id is not None:
+ return
+ record_slack_report_discussion(team_id=team_id, report_id=report_id, task_id=task_id, user_id=user_id)
+ task.signal_report_id = UUID(report_id)
+ task.save(update_fields=["signal_report_id", "updated_at"])
+
+
def create_and_run_task(
*,
team,
@@ -1651,6 +1666,7 @@ def create_and_run_task(
``scheduled_at`` creates the run in NOT_STARTED and defers its workflow until the dispatcher
materializes it at or after that time. The run still stores its complete execution settings.
+
"""
# create_pr=False sessions (research, repo selection, custom agents) can never open the
# billable PR, so the quota gate must not block them.
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index 2488e93c9263..337d1ec64d95 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -643,6 +643,8 @@ class Task(DeletedMetaFields, models.Model):
all_properties["origin_key"] = self.origin_key
if self.channel_id:
all_properties["channel_id"] = str(self.channel_id)
+ if self.signal_report_id:
+ all_properties["signal_report_id"] = str(self.signal_report_id)
if properties:
all_properties.update(properties)
(capture_fn or posthoganalytics.capture)(
diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.py
index b5d7ba85a8b3..b91a50754f81 100644
--- a/products/tasks/backend/tests/test_facade.py
+++ b/products/tasks/backend/tests/test_facade.py
@@ -1493,6 +1493,34 @@ class TestFacadeReadsAndMappers(TestCase):
assert created.latest_run is not None
self.assertEqual(created.latest_run.task_id, created.task_id)
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ def test_slack_report_link_is_idempotent_and_does_not_claim_implementation(self, _mock_workflow):
+ from products.signals.backend.models import (
+ SignalReport,
+ SignalReportAction,
+ SignalReportArtefact,
+ SignalReportTask,
+ )
+
+ report = SignalReport.objects.create(team=self.team, title="Report", summary="Summary")
+ created = facade.create_and_run_task(
+ team=self.team,
+ title="Started from a Slack thread",
+ description="desc",
+ origin_product=facade.TaskOriginProduct.SLACK,
+ user_id=self.user.id,
+ )
+ for _ in range(2):
+ facade.link_slack_task_to_report(
+ team_id=self.team.id, task_id=str(created.task_id), report_id=str(report.id), user_id=self.user.id
+ )
+ assert Task.objects.get(id=created.task_id).signal_report_id == report.id
+ assert SignalReportArtefact.objects.filter(report_id=report.id, task_id=created.task_id).count() == 1
+ assert (
+ SignalReportAction.objects.for_team(self.team.id).get(report_id=report.id, user_id=self.user.id).count == 1
+ )
+ assert not SignalReportTask.objects.filter(report_id=report.id).exists()
+
@patch("products.tasks.backend.logic.services.title_generator.generate_task_title")
def test_create_task_names_from_naming_source_keeping_description_bare(self, mock_title):
# When a client pastes text (stored as an attachment), it sends the pasted content as