:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(tasks): file Slack-created tasks into the creator's #me channel (#75096)
Peter Kirkham807508701b4d
diff --git a/posthog/temporal/ai/slack_app/activities/task_creation.py b/posthog/temporal/ai/slack_app/activities/task_creation.pyindex 0ef465096a9e..85c56716ca24 100644--- a/posthog/temporal/ai/slack_app/activities/task_creation.py+++ b/posthog/temporal/ai/slack_app/activities/task_creation.py@@ -636,6 +636,18 @@ def create_posthog_code_task_for_repo_activity(ai_prefs = resolve_ai_preferences(integration, slack_user_id)+ # File into the creator's personal "#me" channel so the task surfaces in PostHog Desktop's+ # Spaces feed, which is strictly channel-scoped — a NULL-channel task shows up in no space.+ personal_channel_id: uuid.UUID | None = None+ try:+ personal_channel_id = tasks_facade.ensure_personal_channel_id(integration.team_id, user_id)+ except Exception:+ logger.warning(+ "posthog_code_personal_channel_resolution_failed",+ team_id=integration.team_id,+ user_id=user_id,+ )+# 1. Create task + run WITHOUT starting the workflowtry:created = tasks_facade.create_and_run_task(@@ -655,6 +667,7 @@ def create_posthog_code_task_for_repo_activity(runtime_adapter=ai_prefs.runtime_adapter,model=ai_prefs.model,reasoning_effort=ai_prefs.reasoning_effort,+ channel_id=personal_channel_id,)except Exception as e:logger.exception(diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 42187751fe59..b173401f54f2 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -142,6 +142,7 @@ __all__ = ["claim_and_fail_stale_run","delete_sandbox_custom_image","delete_sandbox_environment",+ "ensure_personal_channel_id","ensure_sandbox_custom_image_builder_task","delete_task_automation","edit_task_run_living_artifact",@@ -929,6 +930,7 @@ def create_and_run_task(signal_report_id: str | None = None,internal: bool = False,sandbox_environment_id: str | None = None,+ channel_id: str | UUID | None = None,**extra,) -> contracts.CreatedTaskDTO:"""Create a task and (optionally) kick off its processing workflow.@@ -936,7 +938,12 @@ def create_and_run_task(Thin wrapper over ``Task.create_and_run`` that returns ids + the created run as a DTOinstead of leaking the ORM ``Task``. ``team`` is a core ``posthog.Team`` (not a tasksmodel). Less-common keyword arguments are forwarded verbatim via ``**extra``.++ ``channel_id`` files the task into a channel's feed; left NULL for non-channel surfaces.+ An id the creator can't file into (see ``_visible_channel``) is ignored rather than+ raising — feed placement must never break task creation."""+ channel = _visible_channel(channel_id, team.id, user_id) if channel_id is not None else Nonetask = Task.create_and_run(team=team,title=title,@@ -944,6 +951,7 @@ def create_and_run_task(origin_product=origin_product,user_id=user_id,repository=repository,+ channel=channel,create_pr=create_pr,mode=mode,start_workflow=start_workflow,@@ -5321,26 +5329,36 @@ def _channel_to_dto(channel: Channel) -> contracts.ChannelDTO:)+def _team_channels(team_id: int) -> QuerySet[Channel]:+ # for_team rather than a bare team_id filter so these reads also resolve outside request+ # scope (Temporal activities), where the fail-closed manager raises on an unscoped read.+ return Channel.objects.for_team(team_id)++def _ensure_personal_channel(team_id: int, user_id: int) -> Channel:# select_related so _channel_to_dto doesn't lazy-load created_by per call.+ channels = _team_channels(team_id).select_related("created_by")+ lookup = {+ "team_id": team_id,+ "created_by_id": user_id,+ "channel_type": Channel.ChannelType.PERSONAL,+ "deleted": False,+ }try:- channel, _ = Channel.objects.select_related("created_by").get_or_create(- team_id=team_id,- created_by_id=user_id,- channel_type=Channel.ChannelType.PERSONAL,- deleted=False,- defaults={"name": Channel.PERSONAL_CHANNEL_NAME},- )+ channel, _ = channels.get_or_create(**lookup, defaults={"name": Channel.PERSONAL_CHANNEL_NAME})except IntegrityError:- channel = Channel.objects.select_related("created_by").get(- team_id=team_id,- created_by_id=user_id,- channel_type=Channel.ChannelType.PERSONAL,- deleted=False,- )+ channel = channels.get(**lookup)return channel+def ensure_personal_channel_id(team_id: int, user_id: int) -> UUID:+ """Get-or-create the user's personal "#me" channel and return its id.++ For callers outside a request (Temporal activities) that need somewhere to file a task.+ """+ return _ensure_personal_channel(team_id, user_id).id++def list_channels(team_id: int, user_id: int | None) -> list[contracts.ChannelDTO]:"""All live public channels plus the requester's personal channel (provisioned lazily),personal first, then by name."""@@ -5452,7 +5470,7 @@ def _channel_feed_message_to_dto(message: ChannelFeedMessage) -> contracts.Channdef _visible_channel(channel_id: str | UUID, team_id: int, user_id: int | None) -> Channel | None:"""A channel the requester may read: any live public channel on the team, or theirown personal channel. ``None`` when it's missing or someone else's personal channel."""- channel = Channel.objects.select_related("created_by").filter(id=channel_id, team_id=team_id, deleted=False).first()+ channel = _team_channels(team_id).filter(id=channel_id, deleted=False).first()if channel is None:return Noneif channel.channel_type == Channel.ChannelType.PERSONAL and channel.created_by_id != user_id:diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex 7ec231bc42f8..a5655dd33232 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -495,6 +495,7 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):origin_product: "Task.OriginProduct",user_id: int,repository: str | None = None,+ channel: Channel | None = None,slack_thread_context: Optional["SlackThreadContext"] = None,slack_thread_url: str | None = None,branch: str | None = None,@@ -599,6 +600,7 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):github_integration=github_integration,github_user_integration=github_user_integration,repository=repository,+ channel=channel,internal=internal,json_schema=resolve_schema(output_schema) if output_schema else None,**({"signal_report_id": signal_report_id} if signal_report_id else {}),@@ -768,6 +770,7 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):origin_product: "Task.OriginProduct",user_id: int, # Will be used to validate the tasks feature flag and create a personal api key for interacting with PostHog.repository: str | None = None, # Format: "organization/repository", e.g. "posthog/posthog-js"+ channel: Channel | None = None,create_pr: bool = True,mode: str = "background",slack_thread_context: Optional["SlackThreadContext"] = None,@@ -806,6 +809,7 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):origin_product=origin_product,user_id=user_id,repository=repository,+ channel=channel,slack_thread_context=slack_thread_context,slack_thread_url=slack_thread_url,branch=branch,diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.pyindex 0e039456e70b..16d7963279c8 100644--- a/products/tasks/backend/tests/test_facade.py+++ b/products/tasks/backend/tests/test_facade.py@@ -1,6 +1,7 @@import importlibfrom datetime import timedeltafrom typing import ClassVar+from uuid import uuid4from unittest.mock import patch@@ -17,7 +18,7 @@ from products.tasks.backend.facade import (contracts,warm as warm_facade,)-from products.tasks.backend.models import SandboxCustomImage, SandboxEnvironment, Task, TaskRun+from products.tasks.backend.models import Channel, SandboxCustomImage, SandboxEnvironment, Task, TaskRunfrom products.tasks.backend.prompts import WIZARD_HEAD_BRANCH_PLACEHOLDER, build_wizard_pr_agent_promptFACADE_MODULES = [@@ -587,6 +588,64 @@ class TestFacadeReadsAndMappers(TestCase):self.assertEqual(run.state["pending_dispatch"]["posthog_mcp_scopes"], "full")self.assertEqual(run.state["pending_dispatch"]["user_id"], self.user.id)+ def _make_channel(self, **kwargs) -> Channel:+ # unscoped: no ambient team_scope in these tests, and the fail-closed manager+ # raises on a bare write just as it does on a bare read.+ defaults = {+ "team": self.team,+ "name": "engineering",+ "channel_type": Channel.ChannelType.PUBLIC,+ "created_by": self.user,+ }+ return Channel.objects.unscoped().create(**{**defaults, **kwargs})++ def _make_teammates_personal_channel(self) -> Channel:+ teammate = User.objects.create(email="[email protected]", distinct_id="teammate")+ return self._make_channel(+ name=Channel.PERSONAL_CHANNEL_NAME,+ channel_type=Channel.ChannelType.PERSONAL,+ created_by=teammate,+ )++ @parameterized.expand(+ [+ ("public", lambda self: self._make_channel().id, True),+ ("unknown", lambda _self: uuid4(), False),+ # Someone else's "#me" is private: filing into it would leak the task into+ # their personal feed, so it must be dropped like an unknown id.+ ("other_users_personal", lambda self: self._make_teammates_personal_channel().id, False),+ ]+ )+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")+ def test_create_and_run_task_files_into_channel(self, _name, make_channel_id, expect_filed, _mock_workflow):+ Integration.objects.create(team=self.team, kind="github", config={})+ channel_id = make_channel_id(self)++ created = facade.create_and_run_task(+ team=self.team,+ title="Created via facade",+ description="desc",+ origin_product=facade.TaskOriginProduct.USER_CREATED,+ user_id=self.user.id,+ repository="posthog/posthog",+ channel_id=channel_id,+ )+ self.assertEqual(Task.objects.get(id=created.task_id).channel_id, channel_id if expect_filed else None)++ def test_ensure_personal_channel_id_idempotent_outside_request_scope(self):+ # No ambient team_scope here, like a Temporal activity — guards the for_team scoping.+ first = facade.ensure_personal_channel_id(self.team.id, self.user.id)+ second = facade.ensure_personal_channel_id(self.team.id, self.user.id)+ self.assertEqual(first, second)+ self.assertEqual(+ list(+ Channel.objects.unscoped()+ .filter(team=self.team, channel_type=Channel.ChannelType.PERSONAL, deleted=False)+ .values_list("id", flat=True)+ ),+ [first],+ )+@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")def test_create_wizard_cloud_run_seeds_pending_user_message(self, _mock_workflow):Integration.objects.create(team=self.team, kind="github", config={})