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.

fix(tasks): dedupe slack "PR opened" card per conversation (#68188)

Vojta Bartoš5b5f40e95d54
diff --git a/posthog/temporal/ai/slack_app/activities/task_creation.py b/posthog/temporal/ai/slack_app/activities/task_creation.py
index 777a01768337..d845c76caa8f 100644
--- a/posthog/temporal/ai/slack_app/activities/task_creation.py
+++ b/posthog/temporal/ai/slack_app/activities/task_creation.py
@@ -819,8 +819,6 @@ def _resume_task_with_new_run(
"make your changes, commit, and push to that branch. "
"Do NOT create a new branch or PR.]\n\n" + user_text
)
- extra_state["slack_pr_opened_notified"] = True
- extra_state["slack_notified_pr_url"] = previous_pr_url
extra_state["initial_prompt_override"] = initial_prompt_override
extra_state["pending_user_message"] = initial_prompt_override
diff --git a/products/slack_app/backend/tests/test_followup_forwarding.py b/products/slack_app/backend/tests/test_followup_forwarding.py
index 576a4d1a5c22..75139413a62c 100644
--- a/products/slack_app/backend/tests/test_followup_forwarding.py
+++ b/products/slack_app/backend/tests/test_followup_forwarding.py
@@ -609,7 +609,7 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):
@patch("products.tasks.backend.facade.temporal.execute_task_processing_workflow")
@patch("posthog.models.integration.SlackIntegration")
- def test_terminal_run_seeds_pr_url_into_new_run_state(self, mock_slack_cls, mock_execute_workflow):
+ def test_terminal_run_seeds_pr_context_into_new_run_prompt(self, mock_slack_cls, mock_execute_workflow):
self.task_run.status = self.TaskRun.Status.COMPLETED
self.task_run.output = {"pr_url": "https://github.com/org/repo/pull/1"}
self.task_run.save()
@@ -623,10 +623,12 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):
new_run_id = mock_execute_workflow.call_args.kwargs["run_id"]
new_run = self.TaskRun.objects.get(id=new_run_id)
- assert new_run.state.get("slack_pr_opened_notified") is True
- assert new_run.state.get("slack_notified_pr_url") == "https://github.com/org/repo/pull/1"
+ # Resumed run is told to reuse the PR branch, and carries no per-run notified
+ # flag (the "PR opened" card is deduped on the Task).
assert "gh pr checkout https://github.com/org/repo/pull/1" in new_run.state.get("initial_prompt_override", "")
assert "gh pr checkout https://github.com/org/repo/pull/1" in new_run.state.get("pending_user_message", "")
+ assert "slack_pr_opened_notified" not in new_run.state
+ assert "slack_notified_pr_url" not in new_run.state
@patch("products.slack_app.backend.api.resolve_slack_user", return_value=None)
@patch("posthog.models.integration.SlackIntegration")
diff --git a/products/tasks/backend/migrations/0048_task_state.py b/products/tasks/backend/migrations/0048_task_state.py
new file mode 100644
index 000000000000..c294b68665d9
--- /dev/null
+++ b/products/tasks/backend/migrations/0048_task_state.py
@@ -0,0 +1,17 @@
+# Generated by Django 5.2.14 on 2026-07-03 11:33
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("tasks", "0047_alter_task_origin_product"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="task",
+ name="state",
+ field=models.JSONField(blank=True, default=dict, null=True),
+ ),
+ ]
diff --git a/products/tasks/backend/migrations/max_migration.txt b/products/tasks/backend/migrations/max_migration.txt
index 2459c0de4964..dec57ec74dd0 100644
--- a/products/tasks/backend/migrations/max_migration.txt
+++ b/products/tasks/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0047_alter_task_origin_product
+0048_task_state
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index 3cb96461cd57..6a79f13dc029 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -102,6 +102,9 @@ class Channel(TeamScopedRootMixin):
return f"#{self.name}"
+SLACK_NOTIFIED_PR_URL_STATE_KEY = "slack_notified_pr_url"
+
+
class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):
class OriginProduct(models.TextChoices):
ONBOARDING = "onboarding", "Onboarding"
@@ -212,6 +215,10 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):
help_text="Custom prompt for CI fixes. If blank, a default prompt will be used.",
)
+ # Conversation-level state shared across the task's runs (each resume/follow-up
+ # is a fresh TaskRun), e.g. which PRs have been announced to the Slack thread.
+ state = models.JSONField(default=dict, null=True, blank=True)
+
class Meta:
db_table = "posthog_task"
managed = True
@@ -370,6 +377,22 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):
)
return task_run
+ @property
+ def slack_notified_pr_url(self) -> str | None:
+ """PR URL last announced to this task's Slack thread, if any."""
+ return (self.state or {}).get(SLACK_NOTIFIED_PR_URL_STATE_KEY)
+
+ def mark_slack_pr_notified(self, pr_url: str) -> None:
+ """Record ``pr_url`` as the PR announced to the task's Slack thread. Row-locked
+ merge so it doesn't clobber other keys in the shared state bag."""
+ with transaction.atomic():
+ task = Task.objects.select_for_update().only("id", "state").get(id=self.id)
+ state = dict(task.state or {})
+ state[SLACK_NOTIFIED_PR_URL_STATE_KEY] = pr_url
+ task.state = state
+ task.save(update_fields=["state", "updated_at"])
+ self.state = state
+
def soft_delete(self):
self.deleted = True
self.deleted_at = django_timezone.now()
diff --git a/products/tasks/backend/temporal/process_task/activities/post_slack_update.py b/products/tasks/backend/temporal/process_task/activities/post_slack_update.py
index a33faaab399f..d24fb6a311d0 100644
--- a/products/tasks/backend/temporal/process_task/activities/post_slack_update.py
+++ b/products/tasks/backend/temporal/process_task/activities/post_slack_update.py
@@ -141,24 +141,18 @@ def _post_pr_opened_notification_once(
handler.post_pr_opened(pr_url, task_url, reply_target_slack_user_id=reply_target_slack_user_id)
- _mark_pr_opened_notified(task_run, pr_url)
+ task_run.task.mark_slack_pr_notified(pr_url)
def _is_pr_opened_notified(task_run, pr_url: str) -> bool:
- state = task_run.state or {}
- if not state.get("slack_pr_opened_notified"):
- return False
- notified_url = state.get("slack_notified_pr_url")
- return notified_url == pr_url if notified_url else True
-
-
-def _mark_pr_opened_notified(task_run, pr_url: str) -> None:
- from products.tasks.backend.models import TaskRun
-
- TaskRun.update_state_atomic(
- task_run.id,
- updates={
- "slack_pr_opened_notified": True,
- "slack_notified_pr_url": pr_url,
- },
- )
+ # Dedupe on the Task (the conversation), not the run: a thread spans many runs
+ # and a later one can re-stamp the same pr_url, so per-run state would re-announce.
+ if task_run.task.slack_notified_pr_url == pr_url:
+ return True
+ # Transition fallback: honor the old per-run flag for runs already in flight at
+ # deploy. Drop once none predate the task-level dedupe.
+ legacy_state = task_run.state or {}
+ if legacy_state.get("slack_pr_opened_notified"):
+ legacy_url = legacy_state.get("slack_notified_pr_url")
+ return not legacy_url or legacy_url == pr_url
+ return False
diff --git a/products/tasks/backend/tests/test_models.py b/products/tasks/backend/tests/test_models.py
index c75abd490956..03238a8f209a 100644
--- a/products/tasks/backend/tests/test_models.py
+++ b/products/tasks/backend/tests/test_models.py
@@ -408,6 +408,52 @@ class TestTask(TestCase):
self.assertTrue(task.internal)
+class TestTaskSlackPrNotification(TestCase):
+ organization: ClassVar[Organization]
+ team: ClassVar[Team]
+
+ @classmethod
+ def setUpTestData(cls):
+ cls.organization = Organization.objects.create(name="Test Org")
+ cls.team = Team.objects.create(organization=cls.organization, name="Test Team")
+
+ def _task(self) -> Task:
+ return Task.objects.create(
+ team=self.team,
+ title="Test Task",
+ description="Test Description",
+ origin_product=Task.OriginProduct.SLACK,
+ )
+
+ def test_mark_slack_pr_notified_records_overrides_and_persists(self):
+ # Records the announced PR, overrides on a new one, and survives a reload.
+ task = self._task()
+ self.assertIsNone(task.slack_notified_pr_url)
+
+ pr_1 = "https://github.com/org/repo/pull/1"
+ pr_2 = "https://github.com/org/repo/pull/2"
+ task.mark_slack_pr_notified(pr_1)
+ self.assertEqual(task.slack_notified_pr_url, pr_1)
+
+ task.mark_slack_pr_notified(pr_2)
+ self.assertEqual(task.slack_notified_pr_url, pr_2)
+
+ task.refresh_from_db()
+ self.assertEqual(task.slack_notified_pr_url, pr_2)
+
+ def test_mark_slack_pr_notified_preserves_other_state_keys(self):
+ # It's a merge into the shared state bag, not a wholesale write.
+ task = self._task()
+ task.state = {"unrelated": "keep-me"}
+ task.save(update_fields=["state"])
+
+ task.mark_slack_pr_notified("https://github.com/org/repo/pull/1")
+
+ task.refresh_from_db()
+ self.assertEqual(task.state["unrelated"], "keep-me")
+ self.assertEqual(task.slack_notified_pr_url, "https://github.com/org/repo/pull/1")
+
+
class TestTaskSlug(TestCase):
organization: ClassVar[Organization]
team: ClassVar[Team]
diff --git a/products/tasks/backend/tests/test_post_slack_update.py b/products/tasks/backend/tests/test_post_slack_update.py
index ffb15ef51c86..565b10774ff9 100644
--- a/products/tasks/backend/tests/test_post_slack_update.py
+++ b/products/tasks/backend/tests/test_post_slack_update.py
@@ -47,6 +47,9 @@ class TestPostSlackUpdate(TestCase):
mock_run.id = "run-1"
mock_run.output = {}
mock_run.state = {}
+ # Default the task-level dedupe to unset so the comparison is real, not a
+ # truthy MagicMock; skip-path tests override it.
+ mock_run.task.slack_notified_pr_url = None
for k, v in kwargs.items():
setattr(mock_run, k, v)
return mock_run
@@ -71,13 +74,7 @@ class TestPostSlackUpdate(TestCase):
mock_update_reaction.assert_called_once_with("hedgehog")
mock_post_pr_opened.assert_called_once()
- mock_task_run_class.update_state_atomic.assert_called_once_with(
- "run-1",
- updates={
- "slack_pr_opened_notified": True,
- "slack_notified_pr_url": "https://github.com/org/repo/pull/1",
- },
- )
+ mock_run.task.mark_slack_pr_notified.assert_called_once_with("https://github.com/org/repo/pull/1")
@patch.object(SlackThreadHandler, "post_completion")
@patch.object(SlackThreadHandler, "update_reaction")
@@ -217,13 +214,7 @@ class TestPostSlackUpdate(TestCase):
)
mock_update_reaction.assert_called_once_with("eyes")
mock_post_progress.assert_not_called()
- mock_task_run_class.update_state_atomic.assert_called_once_with(
- "run-1",
- updates={
- "slack_pr_opened_notified": True,
- "slack_notified_pr_url": "https://github.com/org/repo/pull/1",
- },
- )
+ mock_run.task.mark_slack_pr_notified.assert_called_once_with("https://github.com/org/repo/pull/1")
mock_run.save.assert_not_called()
@patch.object(SlackThreadHandler, "post_completion")
@@ -318,6 +309,35 @@ class TestPostSlackUpdate(TestCase):
mock_post_pr_opened.assert_not_called()
mock_delete_progress.assert_called_once()
+ @patch.object(SlackThreadHandler, "delete_progress")
+ @patch.object(SlackThreadHandler, "post_pr_opened")
+ @patch.object(SlackThreadHandler, "update_reaction")
+ @patch.object(SlackThreadHandler, "__init__", return_value=None)
+ @patch("products.tasks.backend.models.TaskRun")
+ def test_run_does_not_repost_pr_a_sibling_run_already_announced(
+ self,
+ mock_task_run_class,
+ mock_handler_init,
+ mock_update_reaction,
+ mock_post_pr_opened,
+ mock_delete_progress,
+ ):
+ # Regression: a fresh run (empty per-run state) must not re-announce a PR a
+ # sibling run already recorded on the shared Task.
+ mock_run = self._make_mock_run(
+ mock_task_run_class.Status.COMPLETED,
+ output={"pr_url": "https://github.com/org/repo/pull/1"},
+ state={},
+ )
+ mock_run.task.slack_notified_pr_url = "https://github.com/org/repo/pull/1"
+ mock_task_run_class.objects.select_related.return_value.get.return_value = mock_run
+
+ post_slack_update(PostSlackUpdateInput(run_id="run-1", slack_thread_context=self.slack_thread_context))
+
+ mock_post_pr_opened.assert_not_called()
+ mock_delete_progress.assert_called_once()
+ mock_run.task.mark_slack_pr_notified.assert_not_called()
+
@patch.object(SlackThreadHandler, "post_pr_opened")
@patch.object(SlackThreadHandler, "update_reaction")
@patch.object(SlackThreadHandler, "__init__", return_value=None)
@@ -348,13 +368,7 @@ class TestPostSlackUpdate(TestCase):
"http://localhost:8000/project/1/tasks/10?runId=run-1",
reply_target_slack_user_id=None,
)
- mock_task_run_class.update_state_atomic.assert_called_once_with(
- "run-1",
- updates={
- "slack_pr_opened_notified": True,
- "slack_notified_pr_url": "https://github.com/org/repo/pull/2",
- },
- )
+ mock_run.task.mark_slack_pr_notified.assert_called_once_with("https://github.com/org/repo/pull/2")
@patch.object(SlackThreadHandler, "delete_progress")
@patch.object(SlackThreadHandler, "post_pr_opened")