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): let the team read runs of shared slack threads (#86951)

Vojta Bartoš3581d3b34265
diff --git a/posthog/temporal/ai/slack_app/activities/task_creation.py b/posthog/temporal/ai/slack_app/activities/task_creation.py
index 1139a6302f56..b06185e1bc0e 100644
--- a/posthog/temporal/ai/slack_app/activities/task_creation.py
+++ b/posthog/temporal/ai/slack_app/activities/task_creation.py
@@ -505,6 +505,7 @@ def create_posthog_code_task_for_repo_activity(
from posthog.models.integration import Integration, SlackIntegration
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
from products.tasks.backend.facade import api as tasks_facade
from products.tasks.backend.facade.temporal import dispatch_task_processing_workflow
@@ -714,6 +715,10 @@ def create_posthog_code_task_for_repo_activity(
"task_run_id": task_run.id,
"mentioning_slack_user_id": slack_user_id,
"last_forwarded_ts": initial_watermark,
+ # Decides whether the whole team may read this thread's task, so it is
+ # resolved here — once, against the live conversation — rather than
+ # re-derived on every request that gates on it.
+ "conversation_type": resolve_conversation_type(slack, event, channel),
},
)
# Track the workflow to link Temporal jobs to Slack threads
diff --git a/products/slack_app/backend/migrations/0014_slackthreadtaskmapping_conversation_type.py b/products/slack_app/backend/migrations/0014_slackthreadtaskmapping_conversation_type.py
new file mode 100644
index 000000000000..17e10a730adb
--- /dev/null
+++ b/products/slack_app/backend/migrations/0014_slackthreadtaskmapping_conversation_type.py
@@ -0,0 +1,26 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("slack_app", "0013_slacksettings_untagged_followup_mode"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="slackthreadtaskmapping",
+ name="conversation_type",
+ field=models.CharField(
+ blank=True,
+ choices=[
+ ("im", "Direct message"),
+ ("mpim", "Group direct message"),
+ ("public_channel", "Public channel"),
+ ("private_channel", "Private channel"),
+ ("unknown", "Unknown"),
+ ],
+ max_length=16,
+ null=True,
+ ),
+ ),
+ ]
diff --git a/products/slack_app/backend/migrations/0015_backfill_slack_thread_conversation_type.py b/products/slack_app/backend/migrations/0015_backfill_slack_thread_conversation_type.py
new file mode 100644
index 000000000000..a91bb10b6ee4
--- /dev/null
+++ b/products/slack_app/backend/migrations/0015_backfill_slack_thread_conversation_type.py
@@ -0,0 +1,28 @@
+from django.db import migrations
+
+
+def backfill_conversation_type(apps, schema_editor):
+ """Classify the direct-message threads we never recorded a conversation type for.
+
+ A `D…` conversation id is a DM, and this is the only classification recoverable without
+ calling Slack. Channel rows stay NULL, which reads as non-private — the same access they
+ have today. DM rows are the ones whose access changes, so they are the ones that matter:
+ without this, every Slack thread that predates the column keeps team-wide read access,
+ including the direct messages.
+ """
+ SlackThreadTaskMapping = apps.get_model("slack_app", "SlackThreadTaskMapping")
+ SlackThreadTaskMapping.objects.filter(conversation_type__isnull=True, channel__startswith="D").update(
+ conversation_type="im"
+ )
+
+
+class Migration(migrations.Migration):
+ # Data migration kept apart from the AddField in 0014 so the schema change never shares a
+ # transaction (and its locks) with the backfill.
+ dependencies = [
+ ("slack_app", "0014_slackthreadtaskmapping_conversation_type"),
+ ]
+
+ operations = [
+ migrations.RunPython(backfill_conversation_type, migrations.RunPython.noop, elidable=True),
+ ]
diff --git a/products/slack_app/backend/migrations/max_migration.txt b/products/slack_app/backend/migrations/max_migration.txt
index 878a0a1050ff..bf80ca89111b 100644
--- a/products/slack_app/backend/migrations/max_migration.txt
+++ b/products/slack_app/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0013_slacksettings_untagged_followup_mode
+0015_backfill_slack_thread_conversation_type
diff --git a/products/slack_app/backend/models.py b/products/slack_app/backend/models.py
index 3632af9cd5f5..076a2ced0efc 100644
--- a/products/slack_app/backend/models.py
+++ b/products/slack_app/backend/models.py
@@ -7,6 +7,16 @@ from posthog.models.utils import UUIDModel
class SlackThreadTaskMapping(UUIDModel):
"""Maps Slack threads to task runs so follow-up messages can be forwarded to the running agent."""
+ class ConversationType(models.TextChoices):
+ """Shape of the Slack conversation a thread lives in, in Slack's own
+ ``conversations.list`` vocabulary so there is no translation layer."""
+
+ IM = "im", "Direct message"
+ MPIM = "mpim", "Group direct message"
+ PUBLIC_CHANNEL = "public_channel", "Public channel"
+ PRIVATE_CHANNEL = "private_channel", "Private channel"
+ UNKNOWN = "unknown", "Unknown"
+
team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="slack_thread_task_mappings")
integration = models.ForeignKey(
"posthog.Integration",
@@ -37,6 +47,12 @@ class SlackThreadTaskMapping(UUIDModel):
# with a strictly larger `ts` (and smaller than the just-arrived message's `ts`) is
# rendered as a diff so the agent catches up on messages it never saw.
last_forwarded_ts = models.CharField(max_length=64, null=True, blank=True)
+ # Resolved once, when the thread's task is created. NULL on rows written before this was
+ # tracked; UNKNOWN when Slack could not tell us. Both read as non-private: an install
+ # missing `groups:read` should keep team-wide read access rather than narrow a shared
+ # thread down to whoever opened it, which would leave the agent's links dead for everyone
+ # else reading along.
+ conversation_type = models.CharField(max_length=16, choices=ConversationType, null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
@@ -60,6 +76,15 @@ class SlackThreadTaskMapping(UUIDModel):
]
+# A direct message is the only conversation with no audience beyond its author, so a task
+# started in one stays with its creator. Everything else — group DMs and channels, public or
+# private — is shared with people who are all on the same team, and anything asked there is
+# already visible to them, so the thread's task is readable team-wide. Keeping this a set of
+# types rather than a boolean on the row means widening or narrowing the rule later is a
+# one-line change here, with no backfill.
+PRIVATE_CONVERSATION_TYPES = frozenset({SlackThreadTaskMapping.ConversationType.IM})
+
+
class SlackUserProfileCache(UUIDModel):
integration = models.ForeignKey(
"posthog.Integration",
diff --git a/products/slack_app/backend/services/slack_conversations.py b/products/slack_app/backend/services/slack_conversations.py
new file mode 100644
index 000000000000..f5f09b83f6ae
--- /dev/null
+++ b/products/slack_app/backend/services/slack_conversations.py
@@ -0,0 +1,92 @@
+"""Resolving what kind of Slack conversation a thread lives in.
+
+The answer decides whether the thread's task is readable by the whole team or stays with
+its creator, so it is resolved once at task creation and stored on the thread mapping
+rather than recomputed per request.
+
+The three steps below are ordered cheapest-first, but the ordering is load-bearing rather
+than an optimization: ``conversations.info`` is the only step that costs a round-trip, and
+it is the one step that cannot answer for a DM. ``im:read`` is not in the scopes we request
+and ``mpim:read`` is still in Slack review, so the call fails outright on a ``D…`` id.
+Steps 1 and 2 settle direct messages without it, leaving the API responsible only for the
+public-vs-private split among channels, where ``channels:read`` and ``groups:read`` do apply.
+"""
+
+from typing import Any
+
+import structlog
+from slack_sdk.errors import SlackApiError
+
+from posthog.models.integration import SlackIntegration
+
+from products.slack_app.backend.models import SlackThreadTaskMapping
+
+logger = structlog.get_logger(__name__)
+
+ConversationType = SlackThreadTaskMapping.ConversationType
+
+# `channel_type` rides on `message` events and is what the event router already keys on to
+# send DMs to the assistant surface. `group` is Slack's wire name for a private channel.
+_CHANNEL_TYPE_TO_CONVERSATION_TYPE = {
+ "im": ConversationType.IM,
+ "mpim": ConversationType.MPIM,
+ "group": ConversationType.PRIVATE_CHANNEL,
+ "channel": ConversationType.PUBLIC_CHANNEL,
+}
+
+
+def resolve_conversation_type(
+ slack: SlackIntegration,
+ event: dict[str, Any],
+ channel_id: str,
+) -> SlackThreadTaskMapping.ConversationType:
+ """The shape of the conversation ``channel_id`` names.
+
+ Never raises: an unresolvable conversation comes back as ``UNKNOWN``, which reads as
+ non-private downstream. Task creation must not fail over this.
+ """
+ channel_type = event.get("channel_type")
+ if channel_type in _CHANNEL_TYPE_TO_CONVERSATION_TYPE:
+ return _CHANNEL_TYPE_TO_CONVERSATION_TYPE[channel_type]
+
+ # `app_mention` carries no `channel_type` and is the primary way a new task starts, so
+ # the id prefix is the only signal left for a DM. Slack discourages relying on prefixes,
+ # which is why it is a fallback and not the first check — but `D…` is unambiguous, and
+ # the alternative (`conversations.info`) is exactly the call we lack the scope to make.
+ # `G…` is deliberately not mapped: it means either a group DM or a legacy private
+ # channel. Both are shared conversations, so the distinction does not change who may
+ # read the task — only which label we store — and the lookup below can try to get it right.
+ if channel_id.startswith("D"):
+ return ConversationType.IM
+
+ return _channel_privacy_from_slack(slack, channel_id)
+
+
+def _channel_privacy_from_slack(
+ slack: SlackIntegration,
+ channel_id: str,
+) -> SlackThreadTaskMapping.ConversationType:
+ """Split public from private for something we already believe is a channel."""
+ try:
+ channel = slack.client.conversations_info(channel=channel_id).get("channel") or {}
+ except SlackApiError as e:
+ # Most likely an install predating `channels:read`/`groups:read`, or a ratelimit.
+ logger.warning(
+ "slack_app_conversation_type_lookup_failed",
+ channel_id=channel_id,
+ error=e.response.get("error"),
+ )
+ return ConversationType.UNKNOWN
+ except Exception:
+ logger.warning("slack_app_conversation_type_lookup_failed", channel_id=channel_id, exc_info=True)
+ return ConversationType.UNKNOWN
+
+ # A group DM reached here only if its id did not start with `D`; `conversations.info`
+ # still labels it, so honour that before falling back to the private/public split.
+ if channel.get("is_im"):
+ return ConversationType.IM
+ if channel.get("is_mpim"):
+ return ConversationType.MPIM
+ if "is_private" not in channel:
+ return ConversationType.UNKNOWN
+ return ConversationType.PRIVATE_CHANNEL if channel["is_private"] else ConversationType.PUBLIC_CHANNEL
diff --git a/products/slack_app/backend/tests/services/test_slack_conversations.py b/products/slack_app/backend/tests/services/test_slack_conversations.py
new file mode 100644
index 000000000000..fd58812d24ca
--- /dev/null
+++ b/products/slack_app/backend/tests/services/test_slack_conversations.py
@@ -0,0 +1,80 @@
+import pytest
+from unittest.mock import MagicMock
+
+from slack_sdk.errors import SlackApiError
+
+from products.slack_app.backend.models import SlackThreadTaskMapping
+from products.slack_app.backend.services.slack_conversations import resolve_conversation_type
+
+ConversationType = SlackThreadTaskMapping.ConversationType
+
+
+def _slack(channel: dict | None = None, error: Exception | None = None) -> MagicMock:
+ slack = MagicMock()
+ if error is not None:
+ slack.client.conversations_info.side_effect = error
+ else:
+ slack.client.conversations_info.return_value = {"channel": channel or {}}
+ return slack
+
+
+class TestResolveConversationType:
+ @pytest.mark.parametrize(
+ "channel_type,expected",
+ [
+ ("im", ConversationType.IM),
+ ("mpim", ConversationType.MPIM),
+ ("group", ConversationType.PRIVATE_CHANNEL),
+ ("channel", ConversationType.PUBLIC_CHANNEL),
+ ],
+ )
+ def test_message_event_channel_type_is_authoritative(self, channel_type: str, expected: str) -> None:
+ slack = _slack()
+
+ result = resolve_conversation_type(slack, {"channel_type": channel_type}, "C123")
+
+ assert result == expected
+ slack.client.conversations_info.assert_not_called()
+
+ def test_app_mention_in_dm_falls_back_to_the_id_prefix(self) -> None:
+ result = resolve_conversation_type(_slack(), {"type": "app_mention"}, "D123")
+
+ assert result == ConversationType.IM
+
+ def test_dm_never_calls_slack(self) -> None:
+ # `conversations.info` on a `D…` id needs `im:read`, which the app does not request —
+ # in production the call fails, so reordering the checks would misclassify every DM
+ # reached through `app_mention`. Stubbing the client hides that, asserting it doesn't.
+ slack = _slack()
+
+ resolve_conversation_type(slack, {"type": "app_mention"}, "D123")
+
+ slack.client.conversations_info.assert_not_called()
+
+ @pytest.mark.parametrize(
+ "channel,expected",
+ [
+ ({"is_private": True}, ConversationType.PRIVATE_CHANNEL),
+ ({"is_private": False}, ConversationType.PUBLIC_CHANNEL),
+ ({"is_mpim": True}, ConversationType.MPIM),
+ ({}, ConversationType.UNKNOWN),
+ ],
+ )
+ def test_app_mention_in_channel_asks_slack(self, channel: dict, expected: str) -> None:
+ result = resolve_conversation_type(_slack(channel), {"type": "app_mention"}, "C123")
+
+ assert result == expected
+
+ @pytest.mark.parametrize(
+ "error",
+ [
+ SlackApiError("missing_scope", {"error": "missing_scope"}),
+ RuntimeError("boom"),
+ ],
+ )
+ def test_unresolvable_channel_is_unknown_rather_than_an_exception(self, error: Exception) -> None:
+ # Task creation must survive this: UNKNOWN reads as non-private downstream, so the
+ # thread keeps the access it would have had before the lookup existed.
+ result = resolve_conversation_type(_slack(error=error), {"type": "app_mention"}, "C123")
+
+ assert result == ConversationType.UNKNOWN
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 6e5c758bfcab..4bd27bb3f7b2 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -2282,6 +2282,28 @@ def task_run_matches_current_ownership(run_id: str | UUID, task_id: str | UUID,
return run is not None and run.matches_task_ownership()
+def _shared_slack_thread_q() -> Q:
+ """Slack tasks whose thread is not a direct message.
+
+ Phrased as "not private" rather than "is a channel" so a mapping we never classified — a
+ row predating the column, or a lookup Slack refused — keeps the team-wide read access it
+ has today instead of silently narrowing to the thread starter.
+
+ The ``origin_product`` test leads so the subquery is only reached for Slack tasks; every
+ other task short-circuits on an indexed column before touching the mapping table.
+ """
+ from products.slack_app.backend.models import ( # noqa: PLC0415 — cross-product import kept off the api import path
+ PRIVATE_CONVERSATION_TYPES,
+ SlackThreadTaskMapping,
+ )
+
+ private_thread = SlackThreadTaskMapping.objects.filter(
+ task_id=OuterRef("pk"),
+ conversation_type__in=sorted(PRIVATE_CONVERSATION_TYPES),
+ )
+ return Q(origin_product=Task.OriginProduct.SLACK) & Q(~Exists(private_thread))
+
+
def task_accessible_for_run_view(
task_id: str | UUID,
team_id: int,
@@ -2300,10 +2322,20 @@ def task_accessible_for_run_view(
Task-bound sandbox callers set ``bypass_visibility`` only after the view verifies that
the OAuth token's ``sandbox_task_id`` matches this task.
+
+ Tasks from a shared Slack conversation are readable by the whole team. Such a thread is
+ multiplayer: every member of the conversation already sees the agent's replies and follows
+ the links in them, so gating those links on the one person who opened the thread makes the
+ reply unusable for everyone else. The task itself is filed in its creator's personal space,
+ so ``task_visibility_q`` alone would hide it. Read-only on purpose — driving the run stays
+ with the creator, whose credentials the sandbox runs under.
+
+ Threads from a direct message are excluded: a DM has no audience beyond its author, so
+ there is nobody the widened read is for. See ``PRIVATE_CONVERSATION_TYPES``.
"""
task_filter = Task.objects.filter(id=task_id, team_id=team_id, deleted=False)
if not bypass_visibility:
- scope_q = task_control_q(user_id) if for_control else task_visibility_q(user_id)
+ scope_q = task_control_q(user_id) if for_control else task_visibility_q(user_id) | _shared_slack_thread_q()
task_filter = task_filter.filter(scope_q)
return task_filter.exists()
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index 73c455488c55..0ca68878dd5e 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -12924,7 +12924,14 @@ class TestSandboxCustomImageAPI(BaseTaskAPITest):
class TestTaskRunSlackTaskApiAccess(BaseTaskAPITest):
- def _create_run(self, *, origin_product: Task.OriginProduct) -> tuple[Task, TaskRun]:
+ def _create_run(
+ self,
+ *,
+ origin_product: Task.OriginProduct,
+ artifacts: list[dict] | None = None,
+ conversation_type: str | None = None,
+ with_mapping: bool = False,
+ ) -> tuple[Task, TaskRun]:
creator = self.create_organization_user("thread-starter")
task = Task.objects.create(
team=self.team,
@@ -12938,13 +12945,27 @@ class TestTaskRunSlackTaskApiAccess(BaseTaskAPITest):
team=self.team,
status=TaskRun.Status.IN_PROGRESS,
environment=TaskRun.Environment.CLOUD,
+ artifacts=artifacts or [],
)
+ if with_mapping:
+ integration = Integration.objects.create(team=self.team, kind="slack", integration_id="T_SLACK", config={})
+ SlackThreadTaskMapping.objects.create(
+ team=self.team,
+ integration=integration,
+ slack_workspace_id="T_SLACK",
+ channel="D123" if conversation_type == "im" else "C123",
+ thread_ts="1234.5678",
+ task=task,
+ task_run=run,
+ mentioning_slack_user_id="U123",
+ conversation_type=conversation_type,
+ )
return task, run
@parameterized.expand(
[
("teammate_cannot_patch_slack_run", Task.OriginProduct.SLACK, "patch", status.HTTP_404_NOT_FOUND),
- ("teammate_cannot_retrieve_slack_run", Task.OriginProduct.SLACK, "get", status.HTTP_404_NOT_FOUND),
+ ("teammate_can_retrieve_slack_run", Task.OriginProduct.SLACK, "get", status.HTTP_200_OK),
(
"teammate_cannot_patch_user_created_run",
Task.OriginProduct.USER_CREATED,
@@ -12978,6 +12999,95 @@ class TestTaskRunSlackTaskApiAccess(BaseTaskAPITest):
self.assertEqual(response.status_code, expected_status)
+ # The agent posts artifact links into the Slack thread, so everyone reading the thread
+ # follows them — not just whoever opened it. Separate from the run-retrieve case above
+ # because this also pins `artifacts_download_by_id` into `_READ_ONLY_ACTIONS`: drop it
+ # from that tuple and the gate flips to the creator-only control predicate.
+ @parameterized.expand(
+ [
+ ("slack_run_artifact", Task.OriginProduct.SLACK, status.HTTP_302_FOUND),
+ ("user_created_run_artifact", Task.OriginProduct.USER_CREATED, status.HTTP_404_NOT_FOUND),
+ ]
+ )
+ @patch("products.tasks.backend.models.TaskRun.publish_stream_state_event")
+ @patch("posthog.storage.object_storage.get_presigned_url")
+ def test_non_creator_artifact_download_by_origin(
+ self,
+ _case_name: str,
+ origin_product: Task.OriginProduct,
+ expected_status: int,
+ mock_presign: MagicMock,
+ _mock_publish_stream_state_event: MagicMock,
+ ) -> None:
+ mock_presign.return_value = "https://example.com/artifact?sig=123"
+ artifact_id = uuid.uuid4().hex
+ task, run = self._create_run(
+ origin_product=origin_product,
+ artifacts=[
+ {
+ "id": artifact_id,
+ "name": "screenshot.png",
+ "type": "output",
+ "content_type": "image/png",
+ "storage_path": "tasks/artifacts/team_1/task_2/run_3/screenshot.png",
+ }
+ ],
+ )
+
+ response = self.client.get(
+ f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/artifacts/{artifact_id}/download/"
+ )
+
+ self.assertEqual(response.status_code, expected_status)
+
+ # The widened read exists so everyone in a Slack thread can follow the agent's links. A DM
+ # has no such audience, so it must not be widened. The `unclassified` case pins the
+ # fail-open direction the backfill relies on: it leaves every non-DM thread NULL, so a gate
+ # that asked "is this known-shared" instead of "is this known-private" would 404 every
+ # thread that predates the column.
+ @parameterized.expand(
+ [
+ ("dm_thread_hidden", "im", status.HTTP_404_NOT_FOUND),
+ ("public_channel_thread_readable", "public_channel", status.HTTP_200_OK),
+ ("private_channel_thread_readable", "private_channel", status.HTTP_200_OK),
+ ("group_dm_thread_readable", "mpim", status.HTTP_200_OK),
+ ("unclassified_thread_readable", None, status.HTTP_200_OK),
+ ]
+ )
+ @patch("products.tasks.backend.models.TaskRun.publish_stream_state_event")
+ def test_non_creator_run_access_by_conversation_type(
+ self,
+ _case_name: str,
+ conversation_type: str | None,
+ expected_status: int,
+ _mock_publish_stream_state_event: MagicMock,
+ ) -> None:
+ task, run = self._create_run(
+ origin_product=Task.OriginProduct.SLACK,
+ conversation_type=conversation_type,
+ with_mapping=True,
+ )
+
+ response = self.client.get(f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/")
+
+ self.assertEqual(response.status_code, expected_status)
+
+ @patch("products.tasks.backend.models.TaskRun.publish_stream_state_event")
+ def test_non_creator_cannot_patch_shared_slack_run(self, _mock_publish_stream_state_event: MagicMock) -> None:
+ task, run = self._create_run(
+ origin_product=Task.OriginProduct.SLACK,
+ conversation_type="public_channel",
+ with_mapping=True,
+ )
+
+ response = self.client.patch(
+ f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/",
+ {"output": {"marker": "from-teammate"}},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+
class TestModelCatalogueAPI(BaseTaskAPITest):
GATEWAY_MODELS = (