: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
fix(tasks): inherit task authorization from spaces (#80869)
Shy Alterc5f4d92c98c7
diff --git a/ee/api/conversation.py b/ee/api/conversation.pyindex a1dbc10d028f..770a8c495ee9 100644--- a/ee/api/conversation.py+++ b/ee/api/conversation.py@@ -6,6 +6,7 @@ from typing import castfrom django.conf import settingsfrom django.core.exceptions import ValidationError+from django.db.models import Qfrom django.utils import timezoneimport pydantic@@ -324,6 +325,14 @@ class ConversationViewSet(# Only single retrieval of a specific conversation is allowed for other users' conversations (if ID known)if self.action != "retrieve":queryset = queryset.filter(user=self.request.user)+ else:+ queryset = queryset.filter(+ Q(task_id__isnull=True)+ | (+ Q(task__team_id=self.team_id, task__deleted=False)+ & tasks_facade.visible_tasks_q(self.request.user.id, relation="task")+ )+ )# For listing or single retrieval, conversations must be from the assistant and have a titleif self.action in ("list", "retrieve"):queryset = queryset.filter(@@ -430,7 +439,9 @@ class ConversationViewSet(task_ids = list({conversation.task_id for conversation in conversations if conversation.task_id is not None})return {str(task_id): task- for task_id, task in tasks_facade.get_conversation_task_dtos(task_ids, self.team_id).items()+ for task_id, task in tasks_facade.get_conversation_task_dtos(+ task_ids, self.team_id, cast(User, self.request.user).id+ ).items()}def get_serializer_context(self):diff --git a/ee/api/tests/test_conversation.py b/ee/api/tests/test_conversation.pyindex 9254166e4eaa..b1d884e27fed 100644--- a/ee/api/tests/test_conversation.py+++ b/ee/api/tests/test_conversation.py@@ -37,7 +37,7 @@ from posthog.temporal.ai.research_agent import ResearchAgentWorkflow, ResearchAgfrom products.posthog_ai.backend.message_routing import SandboxRouteResultfrom products.posthog_ai.backend.models.assistant import Conversation-from products.tasks.backend.models import Task, TaskRun+from products.tasks.backend.models import Channel, Task, TaskRunfrom ee.api.conversation import ConversationViewSet@@ -1484,12 +1484,17 @@ class TestConversationSandboxRoute(APIBaseTest):self.assertFalse(Conversation.objects.filter(id=conversation_id).exists())m_session.return_value.open.assert_not_called()- def test_retrieve_other_users_sandbox_conversation_includes_task(self):- # Read follows the conversation (the share-by-link unit): a teammate handed the link reads its- # backing task too, even though a direct task read would hide a non-creator's task (task_visibility_q).+ def test_retrieve_other_users_private_task_conversation_returns_404(self):teammate = User.objects.create_and_join(self.organization, "[email protected]", "password")+ channel = Channel.objects.unscoped().create(+ team=self.team,+ name=Channel.PERSONAL_CHANNEL_NAME,+ channel_type=Channel.ChannelType.PERSONAL,+ created_by=teammate,+ )task = Task.objects.create(team=self.team,+ channel=channel,title="t",description="secret description",repository="acme/widgets",@@ -1507,9 +1512,7 @@ class TestConversationSandboxRoute(APIBaseTest):response = self.client.get(f"/api/environments/{self.team.id}/conversations/{conversation.id}/")- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(response.json()["task"]["id"], str(task.id))- self.assertEqual(response.json()["task"]["repository"], "acme/widgets")+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)def test_open_other_users_conversation_rejected(self):# Write/send stays creator-only: a teammate can read the shared conversation but cannot provisiondiff --git a/ee/hogai/api/serializers.py b/ee/hogai/api/serializers.pyindex 31e9dd733abe..ae209450ff70 100644--- a/ee/hogai/api/serializers.py+++ b/ee/hogai/api/serializers.py@@ -235,10 +235,7 @@ class TaskSerializer(DataclassSerializer):class ConversationTaskSerializer(TaskSerializer):"""Conversation envelope variant: ``latest_run`` is just the latest run's id, not the nestedrun detail. The frontend only needs the id to reconnect to sandbox logs, and emitting the id- avoids presigning a log URL per conversation.-- Read access here follows the conversation (the share-by-link unit), not per-creator task- visibility — write/send stays creator-gated. See ``tasks_facade.get_conversation_task_dtos``."""+ avoids presigning a log URL per conversation. Task data follows the task's space visibility."""latest_run = serializers.UUIDField( # type: ignore[assignment] # intentional narrowing of the base nested-run field to its idsource="latest_run_id",@@ -266,12 +263,12 @@ class ConversationMinimalSerializer(serializers.ModelSerializer):return Nonetask_dtos = self.context.get("conversation_task_dtos_by_id")- task_dto: TaskDetailDTO | None = (- task_dtos.get(str(conversation.task_id)) if isinstance(task_dtos, dict) else None- )- if task_dto is None:+ if isinstance(task_dtos, dict):+ task_dto: TaskDetailDTO | None = task_dtos.get(str(conversation.task_id))+ else:team = self.context["team"]- task_dto = tasks_facade.get_conversation_task_dtos([conversation.task_id], team.id).get(+ user = self.context["user"]+ task_dto = tasks_facade.get_conversation_task_dtos([conversation.task_id], team.id, user.id).get(conversation.task_id)if task_dto is None:diff --git a/ee/hogai/api/tests/test_serializers.py b/ee/hogai/api/tests/test_serializers.pyindex 902776ffa5eb..a3475d5b4f35 100644--- a/ee/hogai/api/tests/test_serializers.py+++ b/ee/hogai/api/tests/test_serializers.py@@ -513,6 +513,25 @@ class TestConversationMinimalSerializerTaskField(APIBaseTest):data = ConversationMinimalSerializer(conversation, context={"team": self.team, "user": self.user}).dataself.assertIsNone(data["task"])+ def test_minimal_serializer_does_not_refetch_task_missing_from_context_map(self):+ task = self._task()+ conversation = Conversation.objects.create(+ user=self.user,+ team=self.team,+ type=Conversation.Type.ASSISTANT,+ agent_runtime=Conversation.AgentRuntime.SANDBOX,+ task=task,+ )++ with patch("ee.hogai.api.serializers.tasks_facade.get_conversation_task_dtos") as get_task_dtos:+ data = ConversationMinimalSerializer(+ conversation,+ context={"team": self.team, "user": self.user, "conversation_task_dtos_by_id": {}},+ ).data++ self.assertIsNone(data["task"])+ get_task_dtos.assert_not_called()+class TestConversationSerializerArtifactEnrichment(APIBaseTest):"""Test artifact enrichment functionality in the serializer."""diff --git a/posthog/hogql/database/schema/system.py b/posthog/hogql/database/schema/system.pyindex 9c8ee5e202ee..cbc20bcbfc7b 100644--- a/posthog/hogql/database/schema/system.py+++ b/posthog/hogql/database/schema/system.py@@ -2301,20 +2301,41 @@ usage_metrics: PostgresTable = PostgresTable()+task_public_channels: PostgresTable = PostgresTable(+ name="_task_public_channels",+ postgres_table_name="posthog_task_channel",+ predicates=[parse_expr("channel_type = 'public'"), parse_expr("deleted != true")],+ description="Internal list of live project-visible task spaces.",+ fields={+ "id": StringDatabaseField(name="id"),+ "team_id": IntegerDatabaseField(name="team_id"),+ "channel_type": StringDatabaseField(name="channel_type", hidden=True),+ "_deleted": BooleanDatabaseField(name="deleted", hidden=True),+ "deleted": ExpressionField(+ name="deleted",+ expr=ast.Call(name="toInt", args=[ast.Field(chain=["_deleted"])]),+ hidden=True,+ ),+ },+)++tasks: PostgresTable = PostgresTable(name="tasks",postgres_table_name="posthog_task",access_scope="task",- # Mirror the REST API's default filter: internal tasks (signals pipeline, etc.) are not- # exposed to end users. They are excluded entirely from HogQL.- predicates=[parse_expr("internal != true")],- description="Tasks (PostHog Desktop / agent work items); one row per user-facing task (internal pipeline tasks are excluded).",+ predicates=[+ parse_expr("internal != true"),+ parse_expr("channel_id IN (SELECT id FROM system._task_public_channels)"),+ ],+ description="Tasks filed in public project spaces; private, unfiled, and internal tasks are excluded.",fields={"id": StringDatabaseField(name="id", description="Task UUID."),"team_id": IntegerDatabaseField(name="team_id"),"created_by_id": IntegerDatabaseField(name="created_by_id", nullable=True, description="User who created the task."),+ "channel_id": StringDatabaseField(name="channel_id", nullable=True, hidden=True),"github_integration_id": IntegerDatabaseField(name="github_integration_id",nullable=True,@@ -2362,7 +2383,8 @@ task_runs: PostgresTable = PostgresTable(name="task_runs",postgres_table_name="posthog_task_run",access_scope="task",- description="Execution runs of a task; one row per run attempt, with status and outputs.",+ predicates=[parse_expr("task_id IN (SELECT id FROM system.tasks)")],+ description="Execution runs of tasks filed in public project spaces.",fields={"id": StringDatabaseField(name="id", description="Task run UUID."),"team_id": IntegerDatabaseField(name="team_id"),@@ -2525,9 +2547,11 @@ canvases: PostgresTable = PostgresTable(name="canvases",postgres_table_name="posthog_canvas",access_scope="canvas",- # Mirror the REST API's default filter: soft-deleted canvases are not exposed.- predicates=[parse_expr("deleted != true")],- description="Canvases (agent-built sandboxed browser apps, filed into channels); one row per canvas (soft-deleted canvases are excluded).",+ predicates=[+ parse_expr("deleted != true"),+ parse_expr("channel_id IN (SELECT id FROM system._task_public_channels)"),+ ],+ description="Canvases filed in public project spaces; private and soft-deleted canvases are excluded.",fields={"id": StringDatabaseField(name="id", description="Canvas UUID."),"team_id": IntegerDatabaseField(name="team_id"),@@ -2688,6 +2712,7 @@ class SystemTables(TableNode):"_ticket_assignee_roles": TableNode(name="_ticket_assignee_roles", table=ticket_assignee_roles, hidden=True),"support_tickets": TableNode(name="support_tickets", table=support_tickets),"surveys": TableNode(name="surveys", table=surveys),+ "_task_public_channels": TableNode(name="_task_public_channels", table=task_public_channels, hidden=True),"task_runs": TableNode(name="task_runs", table=task_runs),"tags": TableNode(name="tags", table=tags),"tasks": TableNode(name="tasks", table=tasks),diff --git a/posthog/hogql/database/schema/test/test_system_tables.py b/posthog/hogql/database/schema/test/test_system_tables.pyindex b359256d92ab..b124cf416134 100644--- a/posthog/hogql/database/schema/test/test_system_tables.py+++ b/posthog/hogql/database/schema/test/test_system_tables.py@@ -645,11 +645,19 @@ def _create_survey(team: Team, label: str) -> Survey:return Survey.objects.create(team=team, name=f"survey_{label}", type="popover")+def _create_public_task_channel(team: Team, label: str):+ Channel = apps.get_model("tasks", "Channel")++ with team_scope(team.pk):+ return Channel.objects.create(team=team, name=f"channel_{label}")++def _create_task(team: Team, label: str):Task = apps.get_model("tasks", "Task")return Task.objects.create(team=team,+ channel=_create_public_task_channel(team, f"task_{label}"),title=f"task_{label}",description="x",origin_product=Task.OriginProduct.USER_CREATED,@@ -657,11 +665,10 @@ def _create_task(team: Team, label: str):def _create_canvas(team: Team, label: str):- Channel = apps.get_model("tasks", "Channel")Canvas = apps.get_model("canvas", "Canvas")with team_scope(team.pk):- channel = Channel.objects.create(team=team, name=f"channel_for_canvas_{label}")+ channel = _create_public_task_channel(team, f"canvas_{label}")return Canvas.objects.create(team=team, channel=channel, name=f"canvas_{label}")@@ -671,6 +678,7 @@ def _create_task_run(team: Team, label: str):task = Task.objects.create(team=team,+ channel=_create_public_task_channel(team, f"run_{label}"),title=f"task_for_run_{label}",description="x",origin_product=Task.OriginProduct.USER_CREATED,@@ -819,6 +827,7 @@ SYSTEM_TABLE_FACTORIES = [("source_schemas", _create_source_schema),("support_tickets", _create_support_ticket),("surveys", _create_survey),+ ("_task_public_channels", _create_public_task_channel),("tags", _create_tag),("task_runs", _create_task_run),("tasks", _create_task),@@ -942,6 +951,7 @@ class TestSystemTablesCanvasDeletedExclusion(BaseTest):context = HogQLContext(team_id=self.team.pk, enable_select_queries=True, database=db)query, _ = prepare_and_print_ast(parse_select("SELECT id FROM system.canvases"), context, dialect="clickhouse")assert "system__canvases.deleted" in query+ assert "system___task_public_channels" in queryassert f"equals(system__canvases.team_id, {self.team.pk})" in query@@ -975,6 +985,7 @@ class TestSystemTablesTaskInternalExclusion(BaseTest):context = HogQLContext(team_id=self.team.pk, enable_select_queries=True, database=db)query, _ = prepare_and_print_ast(parse_select("SELECT id FROM system.tasks"), context, dialect="clickhouse")assert "system__tasks.internal" in query+ assert "system___task_public_channels" in queryassert f"equals(system__tasks.team_id, {self.team.pk})" in query@@ -985,9 +996,11 @@ class TestSystemTablesTaskInternalExclusionIsolation(NonAtomicBaseTest):def test_internal_tasks_excluded(self):Task = apps.get_model("tasks", "Task")+ channel = _create_public_task_channel(self.team, "internal-exclusion")regular_task = Task.objects.create(team=self.team,+ channel=channel,title="regular",description="x",origin_product=Task.OriginProduct.USER_CREATED,@@ -995,6 +1008,7 @@ class TestSystemTablesTaskInternalExclusionIsolation(NonAtomicBaseTest):)internal_task = Task.objects.create(team=self.team,+ channel=channel,title="internal",description="x",origin_product=Task.OriginProduct.USER_CREATED,@@ -1008,6 +1022,73 @@ class TestSystemTablesTaskInternalExclusionIsolation(NonAtomicBaseTest):assert str(internal_task.pk) not in ids+class TestSystemTablesTaskSpaceVisibilityIsolation(NonAtomicBaseTest):+ CLASS_DATA_LEVEL_SETUP = False++ def test_private_and_unfiled_task_resources_are_excluded(self):+ Channel = apps.get_model("tasks", "Channel")+ Task = apps.get_model("tasks", "Task")+ TaskRun = apps.get_model("tasks", "TaskRun")+ Canvas = apps.get_model("canvas", "Canvas")++ with team_scope(self.team.pk):+ public_channel = Channel.objects.create(team=self.team, name="public-space")+ private_channel = Channel.objects.create(+ team=self.team,+ name=Channel.PERSONAL_CHANNEL_NAME,+ channel_type=Channel.ChannelType.PERSONAL,+ created_by=self.user,+ )+ deleted_channel = Channel.objects.create(team=self.team, name="deleted-space", deleted=True)+ public_canvas = Canvas.objects.create(team=self.team, channel=public_channel, name="public")+ Canvas.objects.create(team=self.team, channel=private_channel, name="private")+ Canvas.objects.create(team=self.team, channel=deleted_channel, name="deleted")++ public_task = Task.objects.create(+ team=self.team,+ channel=public_channel,+ created_by=self.user,+ title="public",+ description="x",+ origin_product=Task.OriginProduct.USER_CREATED,+ )+ private_task = Task.objects.create(+ team=self.team,+ channel=private_channel,+ created_by=self.user,+ title="private",+ description="x",+ origin_product=Task.OriginProduct.SIGNAL_REPORT,+ )+ unfiled_task = Task.objects.create(+ team=self.team,+ created_by=self.user,+ title="unfiled",+ description="x",+ origin_product=Task.OriginProduct.USER_CREATED,+ )+ deleted_channel_task = Task.objects.create(+ team=self.team,+ channel=deleted_channel,+ created_by=self.user,+ title="deleted space",+ description="x",+ origin_product=Task.OriginProduct.USER_CREATED,+ )+ public_run = TaskRun.objects.create(task=public_task, team=self.team)+ TaskRun.objects.create(task=private_task, team=self.team)+ TaskRun.objects.create(task=unfiled_task, team=self.team)+ TaskRun.objects.create(task=deleted_channel_task, team=self.team)++ task_response = execute_hogql_query("SELECT id FROM system.tasks", team=self.team, user=self.user)+ run_response = execute_hogql_query("SELECT id FROM system.task_runs", team=self.team, user=self.user)+ canvas_response = execute_hogql_query("SELECT id FROM system.canvases", team=self.team, user=self.user)++ assert {str(row[0]) for row in task_response.results} == {str(public_task.id)}+ assert {str(row[0]) for row in run_response.results} == {str(public_run.id)}+ assert {str(row[0]) for row in canvas_response.results} == {str(public_canvas.id)}++class TestSystemTablesNotebookMarkdown(NonAtomicBaseTest):CLASS_DATA_LEVEL_SETUP = Falsediff --git a/products/canvas/backend/build_service.py b/products/canvas/backend/build_service.pyindex 1277e355c0ba..37ea5b8d5de8 100644--- a/products/canvas/backend/build_service.py+++ b/products/canvas/backend/build_service.py@@ -508,6 +508,37 @@ def publish_source_project(return canvas, version, build, first_publish+def publish_current_source_version(+ canvas: Canvas,+ expected_current_version_id: str | UUID,+ *,+ user: User | None = None,+ was_impersonated: bool = False,+) -> tuple[Canvas, CanvasBuild]:+ """Queue a build for the current source version without changing source or metadata."""+ with transaction.atomic(), team_scope(canvas.team_id):+ canvas = _claim_canvas_head(+ canvas,+ has_expected_version=True,+ expected_version_id=expected_current_version_id,+ )+ if canvas.current_source_version_id is None:+ raise CanvasVersionConflict(None)+ version = CanvasSourceVersion.objects.for_team(canvas.team_id).get(+ pk=canvas.current_source_version_id,+ canvas_id=canvas.id,+ )+ build = _queue_build(version)+ _log_canvas_activity(+ canvas,+ user=user,+ was_impersonated=was_impersonated,+ activity="published",+ detail=Detail(name=canvas.name),+ )+ return canvas, build++def revert_to_version(canvas: Canvas,version_id: str | UUID,diff --git a/products/canvas/backend/presentation/serializers.py b/products/canvas/backend/presentation/serializers.pyindex bc6d849c311d..ef7755b89713 100644--- a/products/canvas/backend/presentation/serializers.py+++ b/products/canvas/backend/presentation/serializers.py@@ -349,6 +349,12 @@ class CanvasSourceEditSerializer(serializers.Serializer):)+class CanvasPublishCurrentVersionSerializer(serializers.Serializer):+ expected_current_version_id = serializers.UUIDField(+ help_text="Current source version to publish. A changed head returns a 409 version_conflict."+ )++class CanvasSourcePublishResponseSerializer(serializers.Serializer):"""Result of a successful source-project publish."""diff --git a/products/canvas/backend/presentation/views.py b/products/canvas/backend/presentation/views.pyindex cd8fc57596d7..9ccb1f6748ba 100644--- a/products/canvas/backend/presentation/views.py+++ b/products/canvas/backend/presentation/views.py@@ -1,9 +1,9 @@-from typing import Any+from typing import Any, castfrom uuid import UUIDfrom django.conf import settingsfrom django.core.exceptions import ValidationError as DjangoValidationError-from django.db.models import QuerySet+from django.db.models import Q, QuerySetfrom django.utils import timezonefrom drf_spectacular.types import OpenApiTypes@@ -33,6 +33,7 @@ from products.canvas.backend.presentation.serializers import (CanvasDraftSerializer,CanvasPromoteSerializer,CanvasPublishConflictSerializer,+ CanvasPublishCurrentVersionSerializer,CanvasRevertSerializer,CanvasSerializer,CanvasSourceDraftResponseSerializer,@@ -107,6 +108,7 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):"partial_update","destroy","publish",+ "publish_current_version","edit","draft","promote",@@ -114,6 +116,17 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):"build_action",]+ _CREATOR_ONLY_ACTIONS = {+ "partial_update",+ "destroy",+ "publish",+ "edit",+ "draft",+ "promote",+ "revert",+ "build_action",+ }+@extend_schema(parameters=[OpenApiParameter(@@ -133,6 +146,17 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):# DRF resolves all detail actions off this queryset.user = self._request_user()queryset = queryset.filter(tasks_facade.visible_channels_q(user.id if user else None, relation="channel"))+ if self._is_sandbox_authenticated(self.request):+ sandbox_task_id = self._sandbox_task_id(self.request)+ if sandbox_task_id is None:+ return queryset.none()+ queryset = queryset.filter(+ Q(generation_task_id=sandbox_task_id) | Q(source_versions__task_id=sandbox_task_id)+ ).distinct()+ elif self.action in self._CREATOR_ONLY_ACTIONS:+ if user is None:+ return queryset.none()+ queryset = queryset.filter(created_by_id=user.id)if self.action == "list":channel_id = self.request.query_params.get("channel")if channel_id:@@ -146,7 +170,10 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):@extend_schema(operation_id="canvases_create",request=CanvasCreateSerializer,- responses={201: CanvasSerializer},+ responses={+ 201: CanvasSerializer,+ 403: OpenApiResponse(description="The sandbox token is not bound to this task or space."),+ },)def create(self, request: Request, *args: Any, **kwargs: Any) -> Response:"""Create a new, empty canvas in a channel; give it source by publishing a project."""@@ -158,6 +185,14 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):# someone else's personal channel must be refused here too.if not tasks_facade.channel_exists(self.team_id, channel_id, user.id if user else None):return Response({"detail": "Channel not found in this team."}, status=status.HTTP_400_BAD_REQUEST)+ sandbox_task_id = self._sandbox_task_id(request)+ if self._is_sandbox_authenticated(request) and (+ sandbox_task_id is None or not tasks_facade.task_is_in_channel(sandbox_task_id, self.team_id, channel_id)+ ):+ return Response(+ {"detail": "This sandbox can create canvases only in its task's space."},+ status=status.HTTP_403_FORBIDDEN,+ )canvas = Canvas.objects.create(team_id=self.team_id,channel_id=channel_id,@@ -168,7 +203,7 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):# the two at birth so the client can show the run on the# canvas and nest the task under it — composer-initiated# generations have no client-side create to record it.- generation_task_id=self._sandbox_task_id(request),+ generation_task_id=sandbox_task_id,)self._log_canvas_activity(canvas, "created", Detail(name=canvas.name))self._report_canvas_action(@@ -322,6 +357,44 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):diagnostics = validate_source_project(payload.validated_data["project"])return Response({"valid": not has_errors(diagnostics), "diagnostics": diagnostics})+ @extend_schema(+ operation_id="canvases_publish_current_version_create",+ request=CanvasPublishCurrentVersionSerializer,+ responses={+ 200: CanvasBuildSerializer,+ 409: OpenApiResponse(+ response=CanvasPublishConflictSerializer,+ description="The canvas moved past expected_current_version_id.",+ ),+ 429: OpenApiResponse(description="The team's build capacity is exhausted; retry shortly."),+ },+ )+ @action(methods=["POST"], detail=True, url_path="publish-current-version")+ def publish_current_version(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """Queue a build for the current source version without changing source or metadata."""+ canvas = self.get_object()+ payload = CanvasPublishCurrentVersionSerializer(data=request.data)+ payload.is_valid(raise_exception=True)+ try:+ canvas, build = build_service.publish_current_source_version(+ canvas,+ payload.validated_data["expected_current_version_id"],+ user=self._request_user(),+ was_impersonated=is_impersonated(request),+ )+ except build_service.CanvasVersionConflict as conflict:+ return _conflict_response(conflict)+ except build_service.CanvasBuildCapacityExceeded:+ return _capacity_response()+ self._report_canvas_action(+ "canvas published",+ canvas,+ version_id=str(build.source_version_id),+ first_publish=False,+ is_sandbox_publish=self._sandbox_task_id(request) is not None,+ )+ return Response(CanvasBuildSerializer(build).data)+@extend_schema(operation_id="canvases_publish_create",request=CanvasSourcePublishSerializer,@@ -788,21 +861,14 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):return Nonedef _sandbox_task_id(self, request: Request) -> UUID | None:- """The calling task's id when this is a sandbox-stamped MCP call for a- task in this team; None for human/app saves. The task sandbox stamps- every MCP call with an X-PostHog-Task-Id header, but the header alone- is forgeable, so two checks bind it to a real sandbox run: the request- must carry an OAuth token minted under a sandbox app (those tokens are- only created server-side), and the task must have been created by the- requesting user (the sandbox authenticates with the task creator's- credentials)."""+ """Return the calling sandbox's task when its header matches the OAuth binding."""task_id = self._request_task_id(request)if task_id is None or not self._is_sandbox_authenticated(request):return None- user = self._request_user()- if user is None or not tasks_facade.task_owned_by_user(task_id, self.team_id, user.id):+ authenticator = cast(OAuthAccessTokenAuthentication, request.successful_authenticator)+ if authenticator.access_token.sandbox_task_id != task_id:return None- return task_id+ return task_id if tasks_facade.task_exists(task_id, self.team_id) else Nonedef _announce_canvas_created(self, task_id: UUID | None, user: User | None, canvas: Canvas) -> None:"""Announce a canvas's first publish in the generating task's thread.diff --git a/products/canvas/backend/tests/test_canvas_api.py b/products/canvas/backend/tests/test_canvas_api.pyindex a3725d9076bc..43b9acd2d634 100644--- a/products/canvas/backend/tests/test_canvas_api.py+++ b/products/canvas/backend/tests/test_canvas_api.py@@ -1,3 +1,4 @@+from datetime import timedeltafrom typing import Any, castfrom uuid import uuid4@@ -7,14 +8,17 @@ from unittest.mock import patchfrom django.utils import timezonefrom rest_framework import status+from rest_framework.test import APIClientfrom posthog.models.activity_logging.activity_log import ActivityLog+from posthog.models.oauth import OAuthAccessToken, OAuthApplicationfrom posthog.models.scoping import team_scope+from posthog.temporal.oauth import ARRAY_APP_CLIENT_ID_DEVfrom products.canvas.backend import activity_visibility, build_servicefrom products.canvas.backend.models import Canvas, CanvasBuild, CanvasSourceVersionfrom products.canvas.backend.source import synthetic_source_project-from products.tasks.backend.models import Channel+from products.tasks.backend.models import Channel, Taskclass InMemoryStorage:@@ -75,6 +79,30 @@ class CanvasAPIBaseTest(APIBaseTest):assert entry.detail is not Nonereturn entry.detail["changes"]+ def _sandbox_client(self, task_id) -> APIClient:+ application = OAuthApplication.objects.create(+ name="Canvas sandbox",+ client_id=ARRAY_APP_CLIENT_ID_DEV,+ client_type=OAuthApplication.CLIENT_PUBLIC,+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,+ algorithm="RS256",+ redirect_uris="https://example.com/callback",+ organization=self.organization,+ user=self.user,+ )+ access_token = OAuthAccessToken.objects.create(+ user=self.user,+ application=application,+ token=f"pha_canvas_{uuid4().hex}",+ expires=timezone.now() + timedelta(hours=1),+ scope="canvas:read canvas:write task:read",+ scoped_teams=[self.team.id],+ sandbox_task_id=task_id,+ )+ client = APIClient()+ client.credentials(HTTP_AUTHORIZATION=f"Bearer {access_token.token}")+ return client+class TestCanvasCrud(CanvasAPIBaseTest):def test_missing_user_only_sees_public_channels(self):@@ -86,10 +114,14 @@ class TestCanvasCrud(CanvasAPIBaseTest):channel_type=Channel.ChannelType.PERSONAL,created_by=None,)+ deleted = Channel.objects.create(team=self.team, name="deleted", deleted=True)+ unknown = Channel.objects.create(team=self.team, name="unknown", channel_type="unknown")visible_ids = set(Channel.objects.filter(Channel.visible_to_q(None)).values_list("id", flat=True))assert public.id in visible_idsassert personal.id not in visible_ids+ assert deleted.id not in visible_ids+ assert unknown.id not in visible_idsdef test_create_lists_and_filters_by_channel(self):canvas_id = self._create_canvas()@@ -154,6 +186,86 @@ class TestCanvasCrud(CanvasAPIBaseTest):assert self.client.post(f"{base}/publish/", {"project": self._project()}, format="json").status_code == 404assert self.client.delete(f"{base}/").status_code == 404+ def test_task_bound_sandbox_can_create_only_for_its_bound_task(self):+ bound_task = Task.objects.create(+ team=self.team,+ channel=self.channel,+ created_by=self.user,+ title="Bound",+ description="d",+ origin_product=Task.OriginProduct.USER_CREATED,+ )+ other_task = Task.objects.create(+ team=self.team,+ channel=self.channel,+ created_by=self.user,+ title="Other",+ description="d",+ origin_product=Task.OriginProduct.USER_CREATED,+ )+ client = self._sandbox_client(bound_task.id)+ url = f"/api/projects/{self.team.id}/canvases/"++ allowed = client.post(+ url,+ {"name": "Bound canvas", "channel_id": str(self.channel.id)},+ format="json",+ HTTP_X_POSTHOG_TASK_ID=str(bound_task.id),+ )+ denied = client.post(+ url,+ {"name": "Other canvas", "channel_id": str(self.channel.id)},+ format="json",+ HTTP_X_POSTHOG_TASK_ID=str(other_task.id),+ )++ assert allowed.status_code == status.HTTP_201_CREATED+ assert Canvas.objects.unscoped().get(id=allowed.json()["id"]).generation_task_id == bound_task.id+ assert denied.status_code == status.HTTP_403_FORBIDDEN++ def test_task_bound_sandbox_can_read_only_its_canvases(self):+ bound_task = Task.objects.create(+ team=self.team,+ channel=self.channel,+ created_by=self.user,+ title="Bound",+ description="d",+ origin_product=Task.OriginProduct.USER_CREATED,+ )+ other_task = Task.objects.create(+ team=self.team,+ channel=self.channel,+ created_by=self.user,+ title="Other",+ description="d",+ origin_product=Task.OriginProduct.USER_CREATED,+ )+ own_canvas = Canvas.objects.unscoped().create(+ team=self.team,+ channel=self.channel,+ name="Own",+ generation_task_id=bound_task.id,+ )+ other_canvas = Canvas.objects.unscoped().create(+ team=self.team,+ channel=self.channel,+ name="Other",+ generation_task_id=other_task.id,+ )+ client = self._sandbox_client(bound_task.id)++ listing = client.get(+ f"/api/projects/{self.team.id}/canvases/",+ HTTP_X_POSTHOG_TASK_ID=str(bound_task.id),+ )+ other_detail = client.get(+ f"/api/projects/{self.team.id}/canvases/{other_canvas.id}/",+ HTTP_X_POSTHOG_TASK_ID=str(bound_task.id),+ )++ assert [row["id"] for row in listing.json()["results"]] == [str(own_canvas.id)]+ assert other_detail.status_code == status.HTTP_404_NOT_FOUND+def test_create_rejects_unknown_channel(self):response = self.client.post(f"/api/projects/{self.team.id}/canvases/",@@ -234,6 +346,45 @@ class TestCanvasSourceAndPublish(CanvasAPIBaseTest):assert body["current_version_id"] == version_idassert body["project"]["files"]["src/extra.ts"] == "export const x = 1"+ def test_public_members_can_publish_current_source_but_cannot_edit(self):+ canvas_id = self._create_canvas()+ first = self._publish(canvas_id, expected_current_version_id=None)+ assert first.status_code == status.HTTP_200_OK+ version_id = first.json()["current_version_id"]+ other_user = self._create_user("[email protected]")+ self.client.force_login(other_user)+ base = f"/api/projects/{self.team.id}/canvases/{canvas_id}"++ metadata_edit = self.client.patch(f"{base}/", {"name": "Changed"}, format="json")+ source_edit = self.client.post(+ f"{base}/edit/",+ {+ "operations": [{"path": "src/canvas.tsx", "content": "export default function C() { return 2 }"}],+ "expected_current_version_id": version_id,+ },+ format="json",+ )+ source_publish = self.client.post(+ f"{base}/publish/",+ {+ "project": self._project("export default function C() { return 2 }"),+ "expected_current_version_id": version_id,+ },+ format="json",+ )+ current_version_publish = self.client.post(+ f"{base}/publish-current-version/",+ {"expected_current_version_id": version_id},+ format="json",+ )++ assert metadata_edit.status_code == status.HTTP_404_NOT_FOUND+ assert source_edit.status_code == status.HTTP_404_NOT_FOUND+ assert source_publish.status_code == status.HTTP_404_NOT_FOUND+ assert current_version_publish.status_code == status.HTTP_200_OK, current_version_publish.json()+ assert current_version_publish.json()["source_version_id"] == version_id+ assert str(Canvas.objects.unscoped().get(id=canvas_id).current_source_version_id) == version_id+def test_stale_guard_conflicts(self):canvas_id = self._create_canvas()first = self._publish(canvas_id, expected_current_version_id=None)diff --git a/products/canvas/backend/tests/test_canvas_oauth.py b/products/canvas/backend/tests/test_canvas_oauth.pyindex d924813d1439..e568ecf257e6 100644--- a/products/canvas/backend/tests/test_canvas_oauth.py+++ b/products/canvas/backend/tests/test_canvas_oauth.py@@ -1,6 +1,6 @@from datetime import timedeltafrom typing import Any-from uuid import uuid4+from uuid import UUID, uuid4from posthog.test.base import APIBaseTest@@ -19,7 +19,7 @@ class TestCanvasOAuthAccess(APIBaseTest):grandfathered `*` grant; `canvas:read` covers tokens narrowed to an app'sscope ceiling at grant time (which must include the canvas scope)."""- def _bearer(self, scope: str, client_id: str | None = None) -> str:+ def _bearer(self, scope: str, client_id: str | None = None, sandbox_task_id: UUID | None = None) -> str:app = OAuthApplication.objects.create(name="desktop",client_type=OAuthApplication.CLIENT_CONFIDENTIAL,@@ -39,6 +39,7 @@ class TestCanvasOAuthAccess(APIBaseTest):expires=timezone.now() + timedelta(hours=1),scoped_teams=[],scoped_organizations=[],+ sandbox_task_id=sandbox_task_id,)return token.token@@ -66,10 +67,23 @@ class TestCanvasOAuthAccess(APIBaseTest):# bump exists to re-auth these.assert self._list_canvases("task:read task:write dashboard:read") == 403- def _create_canvas(self, *, client_id: str | None, task_header: str | None) -> dict:+ def _create_canvas(+ self,+ *,+ client_id: str | None,+ task_header: str | None,+ sandbox_task: Task | None = None,+ ) -> dict:with team_scope(self.team.id):channel = Channel.objects.create(team=self.team, name="general")- token = self._bearer("*", client_id=client_id)+ if sandbox_task is not None:+ sandbox_task.channel = channel+ sandbox_task.save(update_fields=["channel"])+ token = self._bearer(+ "*",+ client_id=client_id,+ sandbox_task_id=sandbox_task.id if sandbox_task is not None else None,+ )self.client.logout()extra: dict[str, Any] = {"HTTP_X_POSTHOG_TASK_ID": task_header} if task_header else {}res = self.client.post(@@ -87,7 +101,11 @@ class TestCanvasOAuthAccess(APIBaseTest):# sandbox's stamped task header is what records which run produced the# canvas — that link powers the task nesting and generating state.task = Task.objects.create(team=self.team, created_by=self.user, title="Generate canvas")- body = self._create_canvas(client_id=ARRAY_APP_CLIENT_ID_DEV, task_header=str(task.id))+ body = self._create_canvas(+ client_id=ARRAY_APP_CLIENT_ID_DEV,+ task_header=str(task.id),+ sandbox_task=task,+ )assert body["generation_task_id"] == str(task.id)def test_non_sandbox_create_ignores_the_task_header(self):@@ -96,6 +114,18 @@ class TestCanvasOAuthAccess(APIBaseTest):body = self._create_canvas(client_id=None, task_header=str(task.id))assert body["generation_task_id"] is None- def test_sandbox_create_ignores_a_task_outside_the_team(self):- body = self._create_canvas(client_id=ARRAY_APP_CLIENT_ID_DEV, task_header=str(uuid4()))- assert body["generation_task_id"] is None+ def test_sandbox_create_rejects_a_task_outside_the_team(self):+ with team_scope(self.team.id):+ channel = Channel.objects.create(team=self.team, name="general")+ token = self._bearer("*", client_id=ARRAY_APP_CLIENT_ID_DEV, sandbox_task_id=uuid4())+ self.client.logout()++ response = self.client.post(+ f"/api/projects/{self.team.id}/canvases/",+ {"channel_id": str(channel.id), "name": "Signups"},+ format="json",+ HTTP_AUTHORIZATION=f"Bearer {token}",+ HTTP_X_POSTHOG_TASK_ID=str(uuid4()),+ )++ assert response.status_code == 403diff --git a/products/canvas/frontend/generated/api.schemas.ts b/products/canvas/frontend/generated/api.schemas.tsindex a2e7b2804b58..701d51185961 100644--- a/products/canvas/frontend/generated/api.schemas.ts+++ b/products/canvas/frontend/generated/api.schemas.ts@@ -628,6 +628,11 @@ export interface CanvasSourcePublishApi {expected_current_version_id?: string | null}+export interface CanvasPublishCurrentVersionApi {+ /** Current source version to publish. A changed head returns a 409 version_conflict. */+ expected_current_version_id: string+}+/*** Payload for reverting the canvas's head to an existing source version.*/diff --git a/products/canvas/frontend/generated/api.ts b/products/canvas/frontend/generated/api.tsindex 53b27403ae81..fad9b85ff97d 100644--- a/products/canvas/frontend/generated/api.ts+++ b/products/canvas/frontend/generated/api.ts@@ -15,6 +15,7 @@ import type {CanvasBuildsResponseApi,CanvasCreateApi,CanvasPromoteApi,+ CanvasPublishCurrentVersionApi,CanvasRevertApi,CanvasSourceDraftApi,CanvasSourceDraftResponseApi,@@ -337,6 +338,27 @@ export const canvasesPublishCreate = async (})}+export const getCanvasesPublishCurrentVersionCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/canvases/${id}/publish-current-version/`+}++/**+ * Queue a build for the current source version without changing source or metadata.+ */+export const canvasesPublishCurrentVersionCreate = async (+ projectId: string,+ id: string,+ canvasPublishCurrentVersionApi: CanvasPublishCurrentVersionApi,+ options?: RequestInit+): Promise<CanvasBuildApi> => {+ return apiMutator<CanvasBuildApi>(getCanvasesPublishCurrentVersionCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(canvasPublishCurrentVersionApi),+ })+}+export const getCanvasesRevertCreateUrl = (projectId: string, id: string) => {return `/api/projects/${projectId}/canvases/${id}/revert/`}diff --git a/products/canvas/frontend/generated/api.zod.ts b/products/canvas/frontend/generated/api.zod.tsindex 1888ba7fc10a..1308db9ef9d6 100644--- a/products/canvas/frontend/generated/api.zod.ts+++ b/products/canvas/frontend/generated/api.zod.ts@@ -368,6 +368,15 @@ export const CanvasesPublishCreateBody = /* @__PURE__ */ zod}).describe('Payload for publishing a complete canvas source project.')+/**+ * Queue a build for the current source version without changing source or metadata.+ */+export const CanvasesPublishCurrentVersionCreateBody = /* @__PURE__ */ zod.object({+ expected_current_version_id: zod+ .uuid()+ .describe('Current source version to publish. A changed head returns a 409 version_conflict.'),+})+/*** Move the canvas's head back to an existing source version and rebuild it.*/diff --git a/products/canvas/mcp/tools.yaml b/products/canvas/mcp/tools.yamlindex d6e0a370a6af..30b6c1c29567 100644--- a/products/canvas/mcp/tools.yaml+++ b/products/canvas/mcp/tools.yaml@@ -170,6 +170,20 @@ tools:param_overrides:id:description: ID of the canvas whose source to publish.+ canvas-publish-current-version:+ operation: canvases_publish_current_version_create+ enabled: true+ scopes:+ - canvas:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: false+ title: Publish current canvas version+ description: >+ Queue a build for the canvas's current source version without changing its source or metadata. Any project+ member can use this in a public space. Pass the current_version_id read from canvas-source-retrieve. A stale+ value returns a 409 version_conflict.canvas-source-retrieve:operation: canvases_source_retrieveenabled: truediff --git a/products/conversations/frontend/generated/api.schemas.ts b/products/conversations/frontend/generated/api.schemas.tsindex c865af761b66..79349969bf09 100644--- a/products/conversations/frontend/generated/api.schemas.ts+++ b/products/conversations/frontend/generated/api.schemas.ts@@ -159,10 +159,7 @@ export type ConversationTaskApiJsonSchema = { [key: string]: unknown } | null/*** Conversation envelope variant: ``latest_run`` is just the latest run's id, not the nested* run detail. The frontend only needs the id to reconnect to sandbox logs, and emitting the id- * avoids presigning a log URL per conversation.- *- * Read access here follows the conversation (the share-by-link unit), not per-creator task- * visibility — write/send stays creator-gated. See ``tasks_facade.get_conversation_task_dtos``.+ * avoids presigning a log URL per conversation. Task data follows the task's space visibility.*/export interface ConversationTaskApi {id: stringdiff --git a/products/tasks/backend/admin.py b/products/tasks/backend/admin.pyindex 86b89847f0cf..2c4b44bf0058 100644--- a/products/tasks/backend/admin.py+++ b/products/tasks/backend/admin.py@@ -1,13 +1,17 @@+from typing import cast+from django.contrib import admin, messagesfrom django.http import Http404, HttpRequest, HttpResponse, HttpResponseRedirectfrom django.shortcuts import redirectfrom django.urls import path, reversefrom django.utils.html import format_html+from posthog.models.user import Userfrom posthog.storage import object_storagefrom . import loop_servicefrom .models import CodeInvite, CodeInviteRedemption, Loop, LoopTrigger, SandboxSnapshot, Task, TaskRun+from .visibility import task_run_visibility_q, task_visibility_q@admin.register(Task)@@ -27,6 +31,14 @@ class TaskAdmin(admin.ModelAdmin):("Dates", {"fields": ("created_at", "updated_at")}),)+ def get_queryset(self, request: HttpRequest):+ return (+ super()+ .get_queryset(request)+ .filter(team__organization_id__in=cast(User, request.user).organizations.values("id"))+ .filter(task_visibility_q(request.user.id))+ )+@admin.register(TaskRun)class TaskRunAdmin(admin.ModelAdmin):@@ -43,6 +55,14 @@ class TaskRunAdmin(admin.ModelAdmin):("Dates", {"fields": ("created_at", "updated_at", "completed_at")}),)+ def get_queryset(self, request: HttpRequest):+ return (+ super()+ .get_queryset(request)+ .filter(task__team__organization_id__in=cast(User, request.user).organizations.values("id"))+ .filter(task_run_visibility_q(request.user.id))+ )+def get_urls(self) -> list:# Prepended so it isn't shadowed by the default `<path:object_id>/` route.return [diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 5c9b17d433bf..6806e6360ef4 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -104,7 +104,12 @@ from products.tasks.backend.models import ()from products.tasks.backend.pr_urls import merge_pr_outputfrom products.tasks.backend.prompts import build_wizard_pr_agent_prompt, generate_wizard_head_branch-from products.tasks.backend.visibility import task_control_q, task_run_visibility_q, task_visibility_q+from products.tasks.backend.visibility import (+ TEAM_READABLE_ORIGIN_PRODUCTS,+ task_control_q,+ task_run_visibility_q,+ task_visibility_q,+)from . import contracts@@ -248,11 +253,13 @@ __all__ = ["start_task_run","task_accessible_for_run_view","task_exists",+ "task_is_in_channel","task_ids_with_pr_url_subquery","task_run_has_slack_mapping","task_run_is_terminal","task_runtime","task_visible",+ "visible_tasks_q","task_comment_mentions_allowed","list_task_artifacts","list_task_comments",@@ -365,6 +372,35 @@ def _user_basic_info(user: "User | None") -> contracts.TaskUserBasicInfo | None:# Presigned log URLs are cached just under their 1-hour S3 expiry to avoid regeneration._TASK_RUN_LOG_URL_CACHE_TTL = 55 * 60+_TASK_RUN_PUBLIC_STATE_KEYS = frozenset(+ {+ "ai_stage",+ "auto_publish",+ "context_window",+ "custom_image_id",+ "fast_mode",+ "initial_permission_mode",+ "mode",+ "model",+ "pr_authorship_mode",+ "pr_base_branch",+ "provider",+ "reasoning_effort",+ "repositories",+ "repository",+ "resume_from_run_id",+ "rtk_enabled",+ "run_source",+ "runtime_adapter",+ "sandbox_environment_id",+ "slack_thread_url",+ }+)+++def _public_task_run_state(state: dict | None) -> dict:+ return {key: value for key, value in (state or {}).items() if key in _TASK_RUN_PUBLIC_STATE_KEYS}+def _task_run_log_url(run: TaskRun) -> str | None:"""Presigned S3 URL for a run's log, cached. Mirrors ``TaskRunDetailSerializer.get_log_url``."""@@ -409,7 +445,7 @@ def _task_run_detail_to_dto(run: TaskRun) -> contracts.TaskRunDetailDTO:log_url=_task_run_log_url(run),error_message=run.error_message,output=run.output,- state=run.state or {},+ state=_public_task_run_state(run.state),artifacts=run.artifacts or [],created_at=run.created_at,updated_at=run.updated_at,@@ -715,7 +751,11 @@ def get_task_id_for_run(run_id: str | UUID, team_id: int) -> UUID | None:def task_exists(task_id: str | UUID, team_id: int) -> bool:"""Whether a (non-deleted) task exists for the team."""- return Task.objects.filter(id=task_id, team_id=team_id).exists()+ return Task.objects.filter(id=task_id, team_id=team_id, deleted=False).exists()+++def task_is_in_channel(task_id: str | UUID, team_id: int, channel_id: str | UUID) -> bool:+ return Task.objects.filter(id=task_id, team_id=team_id, channel_id=channel_id, deleted=False).exists()def task_owned_by_user(task_id: str | UUID, team_id: int, user_id: int) -> bool:@@ -1081,6 +1121,8 @@ def create_and_run_task(# dark-launch bucket.enforce_self_driving_pr_quota(team, report_id=signal_report_id, stage="task_create")channel = _visible_channel(channel_id, team.id, user_id) if channel_id is not None else None+ if channel is None and not internal and origin_product not in TEAM_READABLE_ORIGIN_PRODUCTS:+ channel = _ensure_personal_channel(team.id, user_id)task = Task.create_and_run(team=team,title=title,@@ -1200,6 +1242,7 @@ def create_task_without_run(For callers that own run creation themselves — e.g. the sandbox warm path, which boots the firstrun via the warming facade. ``team`` is a core ``posthog.Team`` (not a tasks model)."""+ channel = None if origin_product in TEAM_READABLE_ORIGIN_PRODUCTS else _ensure_personal_channel(team.id, user_id)task = Task.create_without_run(team=team,title=title,@@ -1207,6 +1250,7 @@ def create_task_without_run(origin_product=origin_product,user_id=user_id,repository=repository,+ channel=channel,mcp_builtin_agent_key=mcp_builtin_agent_key,)return task.id@@ -1811,7 +1855,9 @@ def _task_automation_to_dto(automation: TaskAutomation) -> contracts.TaskAutomatdef _visible_task_automations(team_id: int, user_id: int | None):- return TaskAutomation.objects.filter(task__team_id=team_id).filter(task_run_visibility_q(user_id))+ return TaskAutomation.objects.filter(task__team_id=team_id, task__deleted=False).filter(+ task_run_visibility_q(user_id)+ )def list_task_automations(team_id: int, user_id: int | None) -> list[contracts.TaskAutomationDTO]:@@ -2128,16 +2174,13 @@ def task_accessible_for_run_view(``for_control`` to use the narrower ``task_control_q`` — public-channel visibility letsteammates watch a run, not drive it.- Slack-originated tasks are the exception: those threads are multiplayer, so any same-team- user can already steer the run from Slack (follow-ups record them as the run's actor, with- sandbox credentials minted for them). The runs API mirrors that and lets team members drive- and watch Slack tasks' runs — otherwise a non-creator actor's sandbox 404s on every callback- (reply relay, log-append heartbeat, completion PATCH) and the thread dies silently.+ Task-bound sandbox callers set ``bypass_visibility`` only after the view verifies that+ the OAuth token's ``sandbox_task_id`` matches this task."""- task_filter = Task.objects.filter(id=task_id, team_id=team_id)+ 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)- task_filter = task_filter.filter(scope_q | Q(origin_product=Task.OriginProduct.SLACK))+ task_filter = task_filter.filter(scope_q)return task_filter.exists()@@ -4185,18 +4228,13 @@ def get_task_detail(return _task_detail_to_dto(task) if task is not None else None-def get_conversation_task_dtos(task_ids: Sequence[str | UUID], team_id: int) -> dict[UUID, contracts.TaskDetailDTO]:- """Task payloads for the Max conversation API, keyed by task id.-- Intentionally team-scoped, with no ``task_visibility_q(user_id)`` gate: the conversation is the- read-share unit, so anyone who can ``retrieve`` a conversation may read its backing task. Broad- read here does not grant action — write/send to a task stays creator-gated in the conversation- viewset (``create``/``open``/``queue``) and at bind time (``validate_task_id``). Direct task reads- (``get_task_detail``) gate by creator because that is the task-enumeration path; this one is not.+def get_conversation_task_dtos(+ task_ids: Sequence[str | UUID], team_id: int, user_id: int | None+) -> dict[UUID, contracts.TaskDetailDTO]:+ """Visible task payloads for the Max conversation API, keyed by task id.- ``latest_run`` (the nested run payload) stays excluded so conversation lists never presign per-row- log URLs; instead a single ``latest_run_id`` subquery carries the latest run id, which the frontend- needs to reconnect to sandbox logs.+ ``latest_run`` stays excluded so conversation lists never presign per-row log URLs. A single+ ``latest_run_id`` subquery carries the id that the frontend needs to reconnect to sandbox logs."""if not task_ids:return {}@@ -4205,7 +4243,8 @@ def get_conversation_task_dtos(task_ids: Sequence[str | UUID], team_id: int) ->TaskRun.objects.filter(task=OuterRef("pk"), team_id=team_id).order_by("-created_at", "-id").values("id")[:1])tasks = (- Task.objects.filter(team_id=team_id, id__in=task_ids)+ Task.objects.filter(team_id=team_id, id__in=task_ids, deleted=False)+ .filter(task_visibility_q(user_id)).select_related("created_by", "team").annotate(_latest_run_id=Subquery(latest_run_id_sq)))@@ -4552,6 +4591,13 @@ def create_task(validated_data = dict(validated_data)validated_data["team"] = teamvalidated_data.setdefault("origin_product", Task.OriginProduct.USER_CREATED)+ if (+ validated_data.get("channel") is None+ and user_id is not None+ and not validated_data.get("internal", False)+ and validated_data["origin_product"] not in TEAM_READABLE_ORIGIN_PRODUCTS+ ):+ validated_data["channel"] = _ensure_personal_channel(team_id, user_id)validated_data["client_provenance"] = client_provenancewarm_branch_provided = "branch" in validated_datawarm_branch = validated_data.pop("branch", None)@@ -4776,7 +4822,7 @@ def update_task(return Nonevalidated_data = dict(validated_data)- # Immutable after creation; origin_product controls visibility, signal_report is set-once.+ # origin_product controls visibility and signal_report is set once.validated_data.pop("signal_report", None)validated_data.pop("signal_report_task_relationship", None)validated_data.pop("origin_product", None)@@ -5764,13 +5810,13 @@ def _slack_repo_research_dto(def resolve_slack_thread_context(- team_id: int, *, channel: str, thread_ts: str, url: str, build_url+ team_id: int, user_id: int | None, *, channel: str, thread_ts: str, url: str, build_url) -> contracts.SlackThreadContextResult:"""Resolve a parsed Slack permalink to its task, runs, and Temporal workflow handles.Caller passes the already-parsed ``(channel, thread_ts)`` and a ``build_url`` callable- (``request.build_absolute_uri``) so the facade stays request-agnostic. Caller also enforces- the internal-debug gate before calling. Mirrors ``TaskViewSet.slack_thread_context``.+ (``request.build_absolute_uri``) so the facade stays request-agnostic. The mapping is filtered+ through the backing task's visibility after the caller enforces the internal-debug gate."""from posthog.storage import object_storage # noqa: PLC0415@@ -5780,7 +5826,8 @@ def resolve_slack_thread_context(mapping = (SlackThreadTaskMapping.objects.select_related("task", "task__created_by")- .filter(channel=channel, thread_ts=thread_ts)+ .filter(channel=channel, thread_ts=thread_ts, team_id=team_id, task__deleted=False)+ .filter(task_run_visibility_q(user_id)).first())if mapping is None:@@ -6035,7 +6082,7 @@ def update_channel(github_integration: Integration | None = None,repositories: list[str] | None = None,) -> contracts.ChannelDTO | str:- """Update a channel, keeping repository configuration creator-owned."""+ """Update a visible channel."""channel = Channel.objects.filter(id=channel_id, team_id=team_id, deleted=False).first()if channel is None:return "not_found"@@ -6044,8 +6091,6 @@ def update_channel(return "not_found"if name is not None:return "personal"- elif repositories is not None and channel.created_by_id != user_id:- return "not_found"update_fields: list[str] = []if name is not None:normalized = normalize_channel_name(name)@@ -6066,13 +6111,15 @@ def update_channel(return _channel_to_dto(channel)-def delete_channel(channel_id: str | UUID, team_id: int) -> str:- """Soft-delete a public channel. Returns ``ok`` / ``not_found`` / ``personal``."""+def delete_channel(channel_id: str | UUID, team_id: int, user_id: int | None) -> str:+ """Soft-delete an empty public channel."""channel = Channel.objects.filter(id=channel_id, team_id=team_id, deleted=False).first()if channel is None:return "not_found"if channel.channel_type == Channel.ChannelType.PERSONAL:- return "personal"+ return "personal" if channel.created_by_id == user_id else "not_found"+ if channel.tasks.filter(deleted=False).exists() or channel.canvases.filter(deleted=False).exists():+ return "not_empty"channel.deleted = Truechannel.save(update_fields=["deleted", "updated_at"])return "ok"@@ -6103,6 +6150,10 @@ def visible_channels_q(user_id: int | None, *, relation: Literal["", "channel"]return Channel.visible_to_q(user_id, relation=relation)+def visible_tasks_q(user_id: int | None, *, relation: Literal["", "task"] = "") -> Q:+ return task_run_visibility_q(user_id) if relation == "task" else task_visibility_q(user_id)++def channel_exists(team_id: int, channel_id: str | UUID, user_id: int | None) -> bool:"""Whether ``channel_id`` is a live channel in this team that the user may see."""return Channel.objects.filter(Channel.visible_to_q(user_id), id=channel_id, team_id=team_id, deleted=False).exists()diff --git a/products/tasks/backend/max_tools.py b/products/tasks/backend/max_tools.pyindex 6121eb1719dd..f1dd2ef9ac3f 100644--- a/products/tasks/backend/max_tools.py+++ b/products/tasks/backend/max_tools.py@@ -7,8 +7,10 @@ from posthog.storage import object_storagefrom ee.hogai.tool import MaxTool+from .facade import api as tasks_facadefrom .models import Task, TaskRunfrom .temporal.client import execute_task_processing_workflow_async+from .visibility import task_control_q, task_visibility_qclass CreateTaskArgs(BaseModel):@@ -74,6 +76,7 @@ By default, the task will be created and immediately executed. Set run=false totask = Task.objects.create(team=self._team,created_by=self._user,+ channel_id=tasks_facade.ensure_personal_channel_id(self._team.id, self._user.id),title=title,description=description,origin_product=Task.OriginProduct.USER_CREATED,@@ -148,7 +151,11 @@ Use this tool when the user wants to:async def _arun_impl(self, task_id: str) -> tuple[str, dict[str, Any]]:@sync_to_asyncdef get_task_and_create_run():- task = Task.objects.filter(id=task_id, team=self._team, deleted=False).first()+ task = (+ Task.objects.filter(id=task_id, team=self._team, deleted=False)+ .filter(task_control_q(self._user.id))+ .first()+ )if not task:return None@@ -207,7 +214,11 @@ Use this tool when the user wants to:async def _arun_impl(self, task_id: str, run_id: str | None = None) -> tuple[str, dict[str, Any]]:@sync_to_asyncdef get_task_and_run():- task = Task.objects.filter(id=task_id, team=self._team, deleted=False).first()+ task = (+ Task.objects.filter(id=task_id, team=self._team, deleted=False)+ .filter(task_visibility_q(self._user.id))+ .first()+ )if not task:return {"error": "not_found", "task_id": task_id}@@ -290,7 +301,11 @@ Use this tool when the user wants to:async def _arun_impl(self, task_id: str, run_id: str | None = None) -> tuple[str, dict[str, Any]]:@sync_to_asyncdef get_task_and_run():- task = Task.objects.filter(id=task_id, team=self._team, deleted=False).first()+ task = (+ Task.objects.filter(id=task_id, team=self._team, deleted=False)+ .filter(task_visibility_q(self._user.id))+ .first()+ )if not task:return {"error": "not_found"}@@ -362,7 +377,11 @@ Use this tool when the user wants to:) -> tuple[str, dict[str, Any]]:@sync_to_asyncdef query_tasks():- qs = Task.objects.filter(team=self._team, deleted=False).order_by("-created_at")+ qs = (+ Task.objects.filter(team=self._team, deleted=False, internal=False)+ .filter(task_visibility_q(self._user.id))+ .order_by("-created_at")+ )if origin_product:qs = qs.filter(origin_product=origin_product)@@ -422,7 +441,11 @@ Use this tool when the user wants to:async def _arun_impl(self, task_id: str, limit: int = 10) -> tuple[str, dict[str, Any]]:@sync_to_asyncdef get_task_and_runs():- task = Task.objects.filter(id=task_id, team=self._team, deleted=False).first()+ task = (+ Task.objects.filter(id=task_id, team=self._team, deleted=False)+ .filter(task_visibility_q(self._user.id))+ .first()+ )if not task:return {"error": "not_found"}diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex 59713d34a07d..b28bf89b1262 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -76,17 +76,21 @@ class Channel(TeamScopedRootMixin):PERSONAL_CHANNEL_NAME = "me"@classmethod- def visible_to_q(cls, user_id: int | None, *, relation: str = "") -> models.Q:+ def visible_to_q(cls, user_id: int | None, *, relation: Literal["", "channel", "task__channel"] = "") -> models.Q:"""The channel-visibility rule as a queryset filter: a personal channel isvisible only to its creator. ``relation`` names the join to ``Channel`` whenfiltering another model's queryset (e.g. ``"channel"``); empty filters``Channel`` rows directly."""- prefix = f"{relation}__" if relation else ""- if user_id is None:- return ~models.Q(**{f"{prefix}channel_type": cls.ChannelType.PERSONAL})- return ~models.Q(**{f"{prefix}channel_type": cls.ChannelType.PERSONAL}) | models.Q(- **{f"{prefix}created_by_id": user_id}- )+ prefix = {"": "", "channel": "channel__", "task__channel": "task__channel__"}[relation]+ visible_q = models.Q(**{f"{prefix}channel_type": cls.ChannelType.PUBLIC})+ if user_id is not None:+ visible_q |= models.Q(+ **{+ f"{prefix}channel_type": cls.ChannelType.PERSONAL,+ f"{prefix}created_by_id": user_id,+ }+ )+ return models.Q(**{f"{prefix}deleted": False}) & visible_q# nosemgrep: prefer-uuid7-django-pk -- mirrors sibling task models in this appid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)@@ -799,6 +803,7 @@ class Task(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,@@ -825,6 +830,7 @@ class Task(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/presentation/serializers.py b/products/tasks/backend/presentation/serializers.pyindex 1da1c78bf3a8..2c32e3a12c5e 100644--- a/products/tasks/backend/presentation/serializers.py+++ b/products/tasks/backend/presentation/serializers.py@@ -646,15 +646,15 @@ class TaskWriteSerializer(serializers.Serializer):cast(serializers.PrimaryKeyRelatedField, self.fields["signal_report"]).queryset = tasks_facade.signal_report_queryset()- # Channel queryset comes from the facade so presentation stays off tasks models.cast(serializers.PrimaryKeyRelatedField, self.fields["channel"]).queryset = tasks_facade.channel_queryset()def validate_channel(self, value):- """Personal channels are private: only their owner may file tasks into them."""request = self.context.get("request")user = getattr(request, "user", None)+ if value is not None and (value.deleted or value.channel_type not in {"public", "personal"}):+ raise serializers.ValidationError("Space not found")if value is not None and value.channel_type == "personal" and value.created_by_id != getattr(user, "id", None):- raise serializers.ValidationError("Personal channels can only be used by their owner")+ raise serializers.ValidationError("Private spaces can only be used by their owner")return valuedef validate_github_integration(self, value):@@ -1521,8 +1521,8 @@ class TaskListQuerySerializer(serializers.Serializer):required=False,default=False,help_text=(- "Staff-only. When true, list every task on the team regardless of creator or channel, "- "bypassing the per-user visibility filter. Ignored for non-staff users."+ "Local development only. With ph_debug=true, list all project tasks for debugging. "+ "Ignored outside local development."),)@@ -1566,6 +1566,10 @@ class ChannelSerializer(DataclassSerializer):]+class ChannelDeleteConflictSerializer(serializers.Serializer):+ detail = serializers.CharField(help_text="Why the space cannot be deleted.")++class ChannelWriteSerializer(serializers.Serializer):"""Request body for creating (resolve-or-create) or renaming a public channel."""diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.pyindex 9ed419913bd2..d64974fc0db9 100644--- a/products/tasks/backend/presentation/views/api.py+++ b/products/tasks/backend/presentation/views/api.py@@ -222,16 +222,13 @@ def _is_internal_debug_team(team_id: int | None) -> bool:def _can_bypass_visibility(request, team_id: int | None) -> bool:- """Whether this request may READ tasks/runs it doesn't own (never write — control stays creator-scoped).-- - Staff users: unconditionally, on any team (support/debugging). No opt-in needed, so staff don't hit- the per-creator 404 when opening a task by URL or streaming its run logs — the frontend can't reliably- thread a query param through every read (the SSE stream doesn't carry one).- - Internal-debug teams: keep the narrower, explicit ``?ph_debug=true`` opt-in (dev/debug workflow).- """- if bool(getattr(request.user, "is_staff", False)):- return True- return _is_internal_debug_team(team_id) and request.query_params.get("ph_debug") == "true"+ """Allow explicit cross-owner reads only in local development."""+ return (+ settings.DEBUG+ and not settings.TEST+ and _is_internal_debug_team(team_id)+ and request.query_params.get("ph_debug") == "true"+ )class _SchemaAwareLimitOffsetPagination(LimitOffsetPagination):@@ -721,7 +718,12 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):)channel, thread_ts = parsedresult = tasks_facade.resolve_slack_thread_context(- self.team_id, channel=channel, thread_ts=thread_ts, url=url, build_url=request.build_absolute_uri+ self.team_id,+ self._user_id(),+ channel=channel,+ thread_ts=thread_ts,+ url=url,+ build_url=request.build_absolute_uri,)if result.outcome == "no_mapping" and (thread := result.no_mapping_thread) is not None:return Response(@@ -1103,9 +1105,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):application = access_token.applicationif application is None or application.client_id not in SANDBOX_OAUTH_APP_CLIENT_IDS:return False- return access_token.sandbox_task_id == UUID(task_id) or "internal_run:read" in (- get_authenticator_scopes(authenticator) or []- )+ return access_token.sandbox_task_id == UUID(task_id)# Actions that only read run state. Everything else mutates or drives the# run, so it requires task control (not just visibility): public-channel@@ -1125,14 +1125,12 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):)def _ensure_task_accessible(self) -> str:- """Gate access to the parent task, mirroring the old ``safely_get_queryset``.-- Staff users (and internal-debug teams via ``?ph_debug=true``) may read another member's runs- through the read-only actions; the bypass never applies to control actions.- """+ """Gate access to the parent task, including exact task-bound sandbox access."""task_id = self._task_id()is_read_only = self.action in self._READ_ONLY_ACTIONS- bypass_visibility = is_read_only and _can_bypass_visibility(self.request, self.team_id)+ bypass_visibility = self._is_sandbox_agent_request(task_id) or (+ is_read_only and _can_bypass_visibility(self.request, self.team_id)+ )if not tasks_facade.task_accessible_for_run_view(task_id,self.team_id,diff --git a/products/tasks/backend/presentation/views/channels_api.py b/products/tasks/backend/presentation/views/channels_api.pyindex 1fd41aaf2ea8..100b4e7033c5 100644--- a/products/tasks/backend/presentation/views/channels_api.py+++ b/products/tasks/backend/presentation/views/channels_api.py@@ -21,6 +21,7 @@ from products.tasks.backend.facade.access import compute_quota_limit_responsefrom products.tasks.backend.facade.compute_quota import ComputeBillingLimitExceededfrom products.tasks.backend.presentation.serializers import (ChannelContextGenerationSerializer,+ ChannelDeleteConflictSerializer,ChannelFeedMessageSerializer,ChannelFeedMessageWriteSerializer,ChannelInstructionsSerializer,@@ -147,13 +148,27 @@ class ChannelViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):raise NotFound()return Response(ChannelSerializer(channel).data)- @extend_schema(responses={204: None}, summary="Delete a public channel")+ @extend_schema(+ responses={+ 204: None,+ 409: OpenApiResponse(+ response=ChannelDeleteConflictSerializer,+ description="The space still contains tasks or canvases.",+ ),+ },+ summary="Delete a public channel",+ )def destroy(self, request, pk=None, **kwargs):- result = tasks_facade.delete_channel(pk, self.team_id)+ result = tasks_facade.delete_channel(pk, self.team_id, self._user_id())if result == "not_found":raise NotFound()if result == "personal":- raise PermissionDenied("Personal channels cannot be deleted")+ raise PermissionDenied("Your private space cannot be deleted")+ if result == "not_empty":+ return Response(+ {"detail": "Remove this space's tasks and canvases before deleting it."},+ status=status.HTTP_409_CONFLICT,+ )return Response(status=status.HTTP_204_NO_CONTENT)@extend_schema(responses={200: ChannelSerializer}, summary="Get a channel")diff --git a/products/tasks/backend/tests/test_admin.py b/products/tasks/backend/tests/test_admin.pyindex c5386b9b9e4f..328cd27e63e9 100644--- a/products/tasks/backend/tests/test_admin.py+++ b/products/tasks/backend/tests/test_admin.py@@ -5,7 +5,7 @@ from unittest.mock import patchfrom django.urls import reverse-from products.tasks.backend.models import Task, TaskRun+from products.tasks.backend.models import Channel, Task, TaskRunclass TestTaskRunAdminDownloadLogs(BaseTest):@@ -72,6 +72,28 @@ class TestTaskRunAdminDownloadLogs(BaseTest):self.assertEqual(resp.status_code, 404)mock_head.assert_not_called()+ def test_other_users_private_space_run_returns_404(self):+ other_user = self._create_user("[email protected]")+ private_channel = Channel.objects.unscoped().create(+ team=self.team,+ name=Channel.PERSONAL_CHANNEL_NAME,+ channel_type=Channel.ChannelType.PERSONAL,+ created_by=other_user,+ )+ private_task = Task.objects.create(+ team=self.team,+ channel=private_channel,+ title="private",+ description="private",+ origin_product=Task.OriginProduct.USER_CREATED,+ created_by=other_user,+ )+ private_run = TaskRun.objects.create(task=private_task, team=self.team)++ response = self.client.get(reverse("admin:tasks_taskrun_download_logs", args=[private_run.id]))++ self.assertEqual(response.status_code, 404)+def test_non_staff_cannot_access(self):self.user.is_staff = Falseself.user.save()diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.pyindex 3b1503c73ece..e020cb772d40 100644--- a/products/tasks/backend/tests/test_api.py+++ b/products/tasks/backend/tests/test_api.py@@ -794,20 +794,10 @@ class TestTaskCreatorScoping(BaseTaskAPITest):@override_settings(CLOUD_DEPLOYMENT="US")-class TestTaskVisibilityInternalDebugTeamBypass(BaseTaskAPITest):- """When the gate (`_is_internal_debug_team`) fires, PostHog employees can- read any teammate's task/run by ID — but the bypass is deliberately narrow:- only the `retrieve` action on TaskViewSet and read-only actions on- TaskRunViewSet. List views, write actions, and other teams remain- creator-scoped. The unaffected cases live in `TestTaskCreatorScoping`- above; the deployment-region requirement is covered by- `TestTaskVisibilityInternalDebugRegionGate`."""-+class TestTaskVisibilityProductionDebugGuard(BaseTaskAPITest):def setUp(self):super().setUp()- # Production checks `team_id == 2 AND CLOUD_DEPLOYMENT == "US"`; tests- # can't easily force the row id, so substitute the test team's id and- # keep the deployment-region clause intact so off-US tests still flip.+ # Make the former production debug-team predicate pass. The local-only guard must still deny access.self._bypass_patch = patch("products.tasks.backend.presentation.views.api._is_internal_debug_team",side_effect=lambda team_id: team_id == self.team.id and settings.CLOUD_DEPLOYMENT == "US",@@ -818,17 +808,14 @@ class TestTaskVisibilityInternalDebugTeamBypass(BaseTaskAPITest):self._bypass_patch.stop()super().tearDown()- def test_retrieve_other_user_task_succeeds(self):+ def test_retrieve_other_user_task_with_ph_debug_returns_404(self):other_user = self.create_organization_user("teammate")task = self.create_task(created_by=other_user)response = self.client.get(f"/api/projects/@current/tasks/{task.id}/?ph_debug=true")- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(response.json()["id"], str(task.id))+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)def test_retrieve_other_user_task_without_ph_debug_still_404s(self):- # The whole point of the param-gated bypass — even on the internal team- # in US-prod, default behavior matches every other team.other_user = self.create_organization_user("teammate")task = self.create_task(created_by=other_user)@@ -836,8 +823,6 @@ class TestTaskVisibilityInternalDebugTeamBypass(BaseTaskAPITest):self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)def test_list_still_excludes_other_user_tasks(self):- # The bypass is scoped to `retrieve` — list still filters by creator even- # with `?ph_debug=true`.other_user = self.create_organization_user("teammate")mine = self.create_task("Mine", created_by=self.user)theirs = self.create_task("Theirs", created_by=other_user)@@ -858,15 +843,13 @@ class TestTaskVisibilityInternalDebugTeamBypass(BaseTaskAPITest):self.assertEqual(response.status_code, status.HTTP_200_OK)self.assertEqual(response.json()["repositories"], [])- def test_list_runs_for_other_user_task_succeeds(self):+ def test_list_runs_for_other_user_task_with_ph_debug_returns_404(self):other_user = self.create_organization_user("teammate")task = self.create_task(created_by=other_user)- run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)+ TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)response = self.client.get(f"/api/projects/@current/tasks/{task.id}/runs/?ph_debug=true")- self.assertEqual(response.status_code, status.HTTP_200_OK)- ids = {item["id"] for item in response.json()["results"]}- self.assertEqual(ids, {str(run.id)})+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)def test_list_runs_for_other_user_task_without_ph_debug_still_404s(self):other_user = self.create_organization_user("teammate")@@ -876,14 +859,13 @@ class TestTaskVisibilityInternalDebugTeamBypass(BaseTaskAPITest):response = self.client.get(f"/api/projects/@current/tasks/{task.id}/runs/")self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)- def test_retrieve_other_user_run_succeeds(self):+ def test_retrieve_other_user_run_with_ph_debug_returns_404(self):other_user = self.create_organization_user("teammate")task = self.create_task(created_by=other_user)run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)response = self.client.get(f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/?ph_debug=true")- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(response.json()["id"], str(run.id))+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)def test_connection_token_on_other_user_run_still_404s_with_ph_debug(self):# connection_token is a GET but mints a write-capable sandbox JWT — the@@ -921,31 +903,23 @@ class TestTaskVisibilityInternalDebugTeamBypass(BaseTaskAPITest):self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)-class TestTaskStaffVisibilityBypass(BaseTaskAPITest):- """Staff users can READ any task/run on the team, unconditionally — no ``?ph_debug=true`` opt-in- (unlike internal-debug teams), because the frontend can't reliably thread a query param through- every read (the SSE stream carries none). The ``all_team_tasks=true`` list filter stays opt-in so- the default list is unchanged. Non-staff users can't reach either, and writes stay creator-scoped.- The internal-debug-team ``?ph_debug=true`` path is covered by ``TestTaskVisibilityInternalDebugTeamBypass``."""-+class TestTaskStaffVisibilityGuard(BaseTaskAPITest):def setUp(self):super().setUp()- # self.user is the authenticated requester (it resolves `@current`); make it staff and- # attribute the tasks under test to a different member so they're "not mine".+ # Make the authenticated requester staff while the task belongs to another project member.self.user.is_staff = Trueself.user.save(update_fields=["is_staff"])self.other_user = self.create_organization_user("teammate")- def test_staff_all_team_tasks_filter_includes_other_user_tasks(self):+ def test_staff_all_team_tasks_filter_excludes_other_user_tasks(self):theirs = self.create_task("Theirs", created_by=self.other_user)response = self.client.get("/api/projects/@current/tasks/?all_team_tasks=true")self.assertEqual(response.status_code, status.HTTP_200_OK)ids = {item["id"] for item in response.json()["results"]}- assert str(theirs.id) in ids+ assert str(theirs.id) not in idsdef test_staff_list_without_filter_still_excludes_other_user_tasks(self):- # The filter is opt-in — the default list stays creator-scoped even for staff.theirs = self.create_task("Theirs", created_by=self.other_user)response = self.client.get("/api/projects/@current/tasks/")@@ -963,13 +937,11 @@ class TestTaskStaffVisibilityBypass(BaseTaskAPITest):ids = {item["id"] for item in response.json()["results"]}assert str(theirs.id) not in ids- def test_staff_retrieve_other_user_task_needs_no_ph_debug(self):- # No opt-in param — a staff user opening a teammate's task by URL just works.+ def test_staff_retrieve_other_user_task_returns_404(self):task = self.create_task(created_by=self.other_user)response = self.client.get(f"/api/projects/@current/tasks/{task.id}/")- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(response.json()["id"], str(task.id))+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)def test_non_staff_retrieve_other_user_task_still_404s(self):self.user.is_staff = False@@ -979,27 +951,22 @@ class TestTaskStaffVisibilityBypass(BaseTaskAPITest):response = self.client.get(f"/api/projects/@current/tasks/{task.id}/")self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)- def test_staff_list_runs_for_other_user_task_needs_no_ph_debug(self):+ def test_staff_list_runs_for_other_user_task_returns_404(self):task = self.create_task(created_by=self.other_user)- run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)+ TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)response = self.client.get(f"/api/projects/@current/tasks/{task.id}/runs/")- self.assertEqual(response.status_code, status.HTTP_200_OK)- ids = {item["id"] for item in response.json()["results"]}- self.assertEqual(ids, {str(run.id)})+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)- def test_staff_list_living_artifacts_for_other_user_run(self):- # Living artifacts are a separate run-read viewset whose gate previously required an- # internal-debug team — staff must reach it on any team too.+ def test_staff_cannot_list_other_user_living_artifacts(self):task = self.create_task(created_by=self.other_user)run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)response = self.client.get(f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/living_artifacts/")- self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")def test_staff_write_on_other_user_task_still_404s(self, _mock_workflow):- # Read-only bypass — staff still can't drive another member's task.task = self.create_task(created_by=self.other_user)response = self.client.post(f"/api/projects/@current/tasks/{task.id}/run/")@@ -1007,16 +974,9 @@ class TestTaskStaffVisibilityBypass(BaseTaskAPITest):class TestTaskVisibilityInternalDebugRegionGate(BaseTaskAPITest):- """The internal-debug bypass keys on team-id 2 — but that's only meaningful in- the US-prod DB. On EU prod, self-hosted, and dev, team-id 2 belongs to some- unrelated organization. The gate must require `CLOUD_DEPLOYMENT == "US"` to- avoid silently granting cross-creator visibility there."""-def setUp(self):super().setUp()- # Same shape as `TestTaskVisibilityInternalDebugTeamBypass.setUp` — the- # `team.id` match would pass on its own, leaving `CLOUD_DEPLOYMENT` as- # the only thing each test varies.+ # Make the former debug-team predicate depend only on the deployment under test.self._bypass_patch = patch("products.tasks.backend.presentation.views.api._is_internal_debug_team",side_effect=lambda team_id: team_id == self.team.id and settings.CLOUD_DEPLOYMENT == "US",@@ -1434,6 +1394,25 @@ class TestTaskAPI(BaseTaskAPITest):self.assertIn("latest_run", data)self.assertIsNone(data["latest_run"])+ def test_run_response_excludes_connection_credentials_from_state(self):+ task = self.create_task("Safe state")+ run = TaskRun.objects.create(+ task=task,+ team=self.team,+ status=TaskRun.Status.IN_PROGRESS,+ state={+ "mode": "interactive",+ "sandbox_connect_token": "secret-token",+ "sandbox_url": "https://sandbox.example.com",+ "pending_dispatch": {"user_id": self.user.id},+ },+ )++ response = self.client.get(f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["state"], {"mode": "interactive"})+def test_create_task(self):response = self.client.post("/api/projects/@current/tasks/",@@ -4627,6 +4606,19 @@ class TestTaskAutomationAPI(BaseTaskAPITest):self.assertEqual(payload["results"][0]["id"], str(automation.id))self.assertEqual(payload["results"][0]["cron_expression"], "0 9 * * *")+ def test_soft_deleted_task_hides_automation(self):+ automation = self.create_automation()+ automation.task.soft_delete()++ response = self.client.get("/api/projects/@current/task_automations/")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["results"], [])+ self.assertEqual(+ self.client.get(f"/api/projects/@current/task_automations/{automation.id}/").status_code,+ status.HTTP_404_NOT_FOUND,+ )+def test_create_automation_rejects_invalid_timezone(self):response = self.client.post("/api/projects/@current/task_automations/",@@ -4864,6 +4856,41 @@ class TestTaskRunAPI(BaseTaskAPITest):response = self.client.get("/api/projects/@current/tasks/not-a-uuid/runs/")self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)+ @patch("products.tasks.backend.models.TaskRun.publish_stream_state_event")+ def test_task_bound_sandbox_can_update_only_its_task(self, _mock_publish_stream_state_event: MagicMock):+ owner = self.create_organization_user("sandbox-owner")+ bound_task = self.create_task(created_by=owner)+ bound_run = TaskRun.objects.create(task=bound_task, team=self.team, status=TaskRun.Status.IN_PROGRESS)+ other_task = self.create_task(created_by=owner)+ other_run = TaskRun.objects.create(task=other_task, team=self.team, status=TaskRun.Status.IN_PROGRESS)+ client = self._sandbox_oauth_client(bound_task.id)++ allowed = client.patch(+ f"/api/projects/@current/tasks/{bound_task.id}/runs/{bound_run.id}/",+ {"stage": "build"},+ format="json",+ )+ denied = client.patch(+ f"/api/projects/@current/tasks/{other_task.id}/runs/{other_run.id}/",+ {"stage": "build"},+ format="json",+ )++ self.assertEqual(allowed.status_code, status.HTTP_200_OK)+ self.assertEqual(denied.status_code, status.HTTP_404_NOT_FOUND)+ other_run.refresh_from_db()+ self.assertIsNone(other_run.stage)++ def test_unbound_sandbox_scope_does_not_bypass_task_visibility(self):+ owner = self.create_organization_user("sandbox-owner")+ task = self.create_task(created_by=owner)+ run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)+ client = self._sandbox_oauth_client(task.id, bound=False, internal_scope=True)++ response = client.get(f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/")++ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)+@parameterized.expand([# Both caller-controlled output writers have to enforce this: the dedicated set_output@@ -6769,7 +6796,7 @@ class TestTaskRunAPI(BaseTaskAPITest):@parameterized.expand([("bound_code_sandbox", ARRAY_APP_CLIENT_ID_DEV, True, False, "agent"),- ("legacy_code_sandbox", ARRAY_APP_CLIENT_ID_DEV, False, True, "agent"),+ ("legacy_code_sandbox", ARRAY_APP_CLIENT_ID_DEV, False, True, "user"),("posthog_ai_sandbox", POSTHOG_AI_APP_CLIENT_ID_DEV, True, False, "agent"),("interactive_code_oauth", ARRAY_APP_CLIENT_ID_DEV, False, False, "user"),("third_party_oauth", "artifact-client", False, False, "user"),@@ -11781,14 +11808,7 @@ class TestSandboxCustomImageAPI(BaseTaskAPITest):mock_workflow.assert_called_once()-class TestTaskRunSlackTaskTeamControl(BaseTaskAPITest):- """Slack-originated tasks are multiplayer: any same-team user may drive their runs.-- Guards the incident where a non-creator's thread follow-up resumed a run whose sandbox- then 404'd on every callback (status PATCH, log append, Slack relay), so the workflow- starved of heartbeats and the thread died silently.- """-+class TestTaskRunSlackTaskApiAccess(BaseTaskAPITest):def _create_run(self, *, origin_product: Task.OriginProduct) -> tuple[Task, TaskRun]:creator = self.create_organization_user("thread-starter")task = Task.objects.create(@@ -11808,8 +11828,8 @@ class TestTaskRunSlackTaskTeamControl(BaseTaskAPITest):@parameterized.expand([- ("teammate_can_patch_slack_run", Task.OriginProduct.SLACK, "patch", status.HTTP_200_OK),- ("teammate_can_retrieve_slack_run", Task.OriginProduct.SLACK, "get", status.HTTP_200_OK),+ ("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_cannot_patch_user_created_run",Task.OriginProduct.USER_CREATED,diff --git a/products/tasks/backend/tests/test_channels_api.py b/products/tasks/backend/tests/test_channels_api.pyindex afdf06da2af4..35225a991631 100644--- a/products/tasks/backend/tests/test_channels_api.py+++ b/products/tasks/backend/tests/test_channels_api.py@@ -168,7 +168,7 @@ class ChannelsAPITestCase(TestCase):self.assertEqual(created.json()["github_integration"], integration.id)@patch("posthog.models.integration.GitHubIntegration.list_all_cached_repositories")- def test_only_creator_can_configure_public_channel_repositories(self, list_repositories):+ def test_project_member_can_configure_or_rename_public_channel(self, list_repositories):list_repositories.return_value = [{"full_name": "posthog/posthog"}]integration = Integration.objects.create(team=self.team, kind="github", integration_id="1", config={})channel_id = self.client.post(self._channels_url(), {"name": "growth"}).json()["id"]@@ -181,14 +181,14 @@ class ChannelsAPITestCase(TestCase):format="json",)- self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)channel = Channel.objects.unscoped().get(id=channel_id)- self.assertEqual(channel.repositories, [])- self.assertIsNone(channel.github_integration_id)+ self.assertEqual(channel.repositories, ["posthog/posthog"])+ self.assertEqual(channel.github_integration_id, integration.id)renamed = other_client.patch(f"{self._channels_url()}{channel_id}/", {"name": "renamed"}, format="json")self.assertEqual(renamed.status_code, status.HTTP_200_OK, renamed.content)- self.assertEqual(renamed.json()["name"], "renamed")+ self.assertEqual(Channel.objects.unscoped().get(id=channel_id).name, "renamed")def test_public_channel_task_is_readable_but_not_controllable_by_teammates(self):channel_id = self.client.post(self._channels_url(), {"name": "growth"}).json()["id"]@@ -217,19 +217,114 @@ class ChannelsAPITestCase(TestCase):status.HTTP_404_NOT_FOUND,)- def test_task_in_personal_channel_stays_private(self):+ @parameterized.expand(+ [+ ("explicit", True),+ ("default", False),+ ]+ )+ def test_task_in_private_space_stays_private(self, _name: str, select_channel: bool):self.client.get(self._channels_url())personal = Channel.objects.unscoped().get(team=self.team, channel_type=Channel.ChannelType.PERSONAL)- created = self.client.post(- self._tasks_url(),- {"title": "Secret", "description": "mine", "channel": str(personal.id)},- )+ payload = {"title": "Secret", "description": "mine"}+ if select_channel:+ payload["channel"] = str(personal.id)+ created = self.client.post(self._tasks_url(), payload)self.assertEqual(created.status_code, status.HTTP_201_CREATED, created.content)+ self.assertEqual(created.json()["channel"], str(personal.id))other_client = APIClient()other_client.force_authenticate(self.other_user)listed = other_client.get(self._tasks_url(), {"channel": str(personal.id)}).json()["results"]self.assertEqual(listed, [])+ self.assertEqual(+ other_client.get(f"{self._tasks_url()}{created.json()['id']}/").status_code,+ status.HTTP_404_NOT_FOUND,+ )++ def test_team_readable_origin_does_not_widen_private_space(self):+ self.client.get(self._channels_url())+ personal = Channel.objects.unscoped().get(team=self.team, channel_type=Channel.ChannelType.PERSONAL)+ task = Task.objects.create(+ team=self.team,+ created_by=self.user,+ channel=personal,+ title="Private signal task",+ description="private",+ origin_product=Task.OriginProduct.SIGNAL_REPORT,+ )++ other_client = APIClient()+ other_client.force_authenticate(self.other_user)++ self.assertEqual(+ other_client.get(f"{self._tasks_url()}{task.id}/").status_code,+ status.HTTP_404_NOT_FOUND,+ )++ def test_task_controller_can_move_task_between_public_spaces(self):+ first = self.client.post(self._channels_url(), {"name": "first"}).json()["id"]+ second = self.client.post(self._channels_url(), {"name": "second"}).json()["id"]+ task = self.client.post(+ self._tasks_url(),+ {"title": "Move me", "description": "d", "channel": first},+ ).json()++ response = self.client.patch(f"{self._tasks_url()}{task['id']}/", {"channel": second}, format="json")++ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)+ self.assertEqual(str(Task.objects.get(id=task["id"]).channel_id), second)++ def test_task_controller_can_move_public_task_to_private_space(self):+ public_space_id = self.client.post(self._channels_url(), {"name": "shared"}).json()["id"]+ private_space_id = next(+ space["id"] for space in self.client.get(self._channels_url()).json() if space["channel_type"] == "personal"+ )+ task = self.client.post(+ self._tasks_url(),+ {"title": "Move private", "description": "d", "channel": public_space_id},+ ).json()++ moved = self.client.patch(+ f"{self._tasks_url()}{task['id']}/",+ {"channel": private_space_id},+ format="json",+ )+ other_client = APIClient()+ other_client.force_authenticate(self.other_user)++ self.assertEqual(moved.status_code, status.HTTP_200_OK, moved.content)+ self.assertEqual(moved.json()["channel"], private_space_id)+ self.assertEqual(+ other_client.get(f"{self._tasks_url()}{task['id']}/").status_code,+ status.HTTP_404_NOT_FOUND,+ )++ clear = self.client.patch(f"{self._tasks_url()}{task['id']}/", {"channel": None}, format="json")+ self.assertEqual(clear.status_code, status.HTTP_200_OK)+ self.assertIsNone(Task.objects.get(id=task["id"]).channel_id)++ def test_project_member_can_delete_an_empty_public_space(self):+ channel_id = self.client.post(self._channels_url(), {"name": "empty"}).json()["id"]+ other_client = APIClient()+ other_client.force_authenticate(self.other_user)++ self.assertEqual(+ other_client.delete(f"{self._channels_url()}{channel_id}/").status_code,+ status.HTTP_204_NO_CONTENT,+ )++ def test_non_empty_public_space_cannot_be_deleted(self):+ channel_id = self.client.post(self._channels_url(), {"name": "active"}).json()["id"]+ self.client.post(+ self._tasks_url(),+ {"title": "Keep me", "description": "d", "channel": channel_id},+ )++ response = self.client.delete(f"{self._channels_url()}{channel_id}/")++ self.assertEqual(response.status_code, status.HTTP_409_CONFLICT)+ self.assertFalse(Channel.objects.unscoped().get(id=channel_id).deleted)def test_cannot_file_task_into_someone_elses_personal_channel(self):self.client.get(self._channels_url())diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.pyindex 0e32c2e1e0d8..451ae59f0b37 100644--- a/products/tasks/backend/tests/test_facade.py+++ b/products/tasks/backend/tests/test_facade.py@@ -243,7 +243,7 @@ class TestFacadeReadsAndMappers(TestCase):other_team = Team.objects.create(organization=self.organization, name="Other team")TaskRun.objects.create(task=task, team=other_team, status=TaskRun.Status.IN_PROGRESS)- dtos = facade.get_conversation_task_dtos([task.id], self.team.id)+ dtos = facade.get_conversation_task_dtos([task.id], self.team.id, self.user.id)self.assertEqual(set(dtos.keys()), {task.id})dto = dtos[task.id]@@ -253,15 +253,21 @@ class TestFacadeReadsAndMappers(TestCase):# The nested run payload stays excluded (no presigned log URLs); only the id is carried.self.assertIsNone(dto.latest_run)self.assertEqual(dto.latest_run_id, latest.id)- self.assertEqual(facade.get_conversation_task_dtos([task.id], other_team.id), {})+ self.assertEqual(facade.get_conversation_task_dtos([task.id], other_team.id, self.user.id), {})def test_get_conversation_task_dtos_latest_run_id_none_without_runs(self):task = self._make_task(title="No runs")- dto = facade.get_conversation_task_dtos([task.id], self.team.id)[task.id]+ dto = facade.get_conversation_task_dtos([task.id], self.team.id, self.user.id)[task.id]self.assertIsNone(dto.latest_run_id)+ def test_get_conversation_task_dtos_excludes_soft_deleted_task(self):+ task = self._make_task(title="Deleted conversation task")+ task.soft_delete()++ self.assertEqual(facade.get_conversation_task_dtos([task.id], self.team.id, self.user.id), {})+def test_get_conversation_task_dtos_is_cheap_for_many_tasks(self):tasks = [self._make_task(title=f"task-{i}") for i in range(5)]for task in tasks:@@ -269,7 +275,7 @@ class TestFacadeReadsAndMappers(TestCase):# A single query with the latest-run-id subquery — no per-task run lookup, no N+1.with self.assertNumQueries(1):- dtos = facade.get_conversation_task_dtos([t.id for t in tasks], self.team.id)+ dtos = facade.get_conversation_task_dtos([t.id for t in tasks], self.team.id, self.user.id)for task in tasks:self.assertIsNotNone(dtos[task.id].latest_run_id)@@ -742,7 +748,13 @@ class TestFacadeReadsAndMappers(TestCase):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)+ task = Task.objects.select_related("channel").get(id=created.task_id)+ if expect_filed:+ self.assertEqual(task.channel_id, channel_id)+ else:+ assert task.channel is not None+ self.assertEqual(task.channel.channel_type, Channel.ChannelType.PERSONAL)+ self.assertEqual(task.channel.created_by_id, self.user.id)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.diff --git a/products/tasks/backend/tests/test_max_tools.py b/products/tasks/backend/tests/test_max_tools.pyindex da2f06cfcfe7..b72b8a34ae16 100644--- a/products/tasks/backend/tests/test_max_tools.py+++ b/products/tasks/backend/tests/test_max_tools.py@@ -17,7 +17,7 @@ from products.tasks.backend.max_tools import (ListTasksTool,RunTaskTool,)-from products.tasks.backend.models import Task, TaskRun+from products.tasks.backend.models import Channel, Task, TaskRunclass BaseTaskToolTest(BaseTest):@@ -99,6 +99,28 @@ class BaseTaskToolTest(BaseTest):):return await sync_to_async(self._create_task_run_sync)(task, status, stage, branch, error_message, output)+ def _create_other_users_private_task_sync(self) -> tuple[Task, TaskRun]:+ other_user = self._create_user("[email protected]")+ channel = Channel.objects.unscoped().create(+ team=self.team,+ name=Channel.PERSONAL_CHANNEL_NAME,+ channel_type=Channel.ChannelType.PERSONAL,+ created_by=other_user,+ )+ task = Task.objects.create(+ team=self.team,+ channel=channel,+ title="Private task",+ description="Private description",+ origin_product=Task.OriginProduct.SIGNAL_REPORT,+ created_by=other_user,+ )+ run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)+ return task, run++ async def _create_other_users_private_task(self) -> tuple[Task, TaskRun]:+ return await sync_to_async(self._create_other_users_private_task_sync)()+class TestCreateTaskTool(BaseTaskToolTest):@patch("products.tasks.backend.max_tools.execute_task_processing_workflow_async")@@ -118,10 +140,13 @@ class TestCreateTaskTool(BaseTaskToolTest):assert "url" in artifactassert artifact["title"] == "New Task"- task = await sync_to_async(Task.objects.get)(id=artifact["task_id"])+ task = await sync_to_async(Task.objects.select_related("channel").get)(id=artifact["task_id"])assert task.title == "New Task"assert task.description == "Task description"assert task.repository == "posthog/posthog-js"+ assert task.channel is not None+ assert task.channel.channel_type == Channel.ChannelType.PERSONAL+ assert task.channel.created_by_id == self.user.idmock_execute_workflow.assert_called_once()@pytest.mark.django_db@@ -248,6 +273,19 @@ class TestRunTaskTool(BaseTaskToolTest):assert call_kwargs["user_id"] == self.user.idassert "run_id" in call_kwargs+ @patch("products.tasks.backend.max_tools.execute_task_processing_workflow_async")+ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_run_task_in_other_users_private_space(self, mock_execute_workflow):+ task, _run = await self._create_other_users_private_task()+ tool = self._create_tool(RunTaskTool)++ content, artifact = await tool._arun_impl(task_id=str(task.id))++ assert "not found" in content+ assert artifact["error"] == "not_found"+ mock_execute_workflow.assert_not_called()+@patch("products.tasks.backend.max_tools.execute_task_processing_workflow_async")@pytest.mark.django_db@pytest.mark.asyncio@@ -354,6 +392,17 @@ class TestGetTaskRunTool(BaseTaskToolTest):assert "not found" in contentassert artifact["error"] == "not_found"+ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_get_task_run_in_other_users_private_space(self):+ task, _run = await self._create_other_users_private_task()+ tool = self._create_tool(GetTaskRunTool)++ content, artifact = await tool._arun_impl(task_id=str(task.id))++ assert "not found" in content+ assert artifact["error"] == "not_found"+@parameterized_class(("status", "expected_display"),@@ -505,6 +554,17 @@ class TestGetTaskRunLogsTool(BaseTaskToolTest):assert "not found" in contentassert artifact["error"] == "not_found"+ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_get_logs_in_other_users_private_space(self):+ task, _run = await self._create_other_users_private_task()+ tool = self._create_tool(GetTaskRunLogsTool)++ content, artifact = await tool._arun_impl(task_id=str(task.id))++ assert "not found" in content+ assert artifact["error"] == "not_found"+class TestListTasksTool(BaseTaskToolTest):@pytest.mark.django_db@@ -670,6 +730,17 @@ class TestListTasksTool(BaseTaskToolTest):assert f"ID: {task.id}" in content+ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_list_tasks_excludes_other_users_private_space(self):+ await self._create_other_users_private_task()+ visible = await self._create_task("Visible")+ tool = self._create_tool(ListTasksTool)++ _content, artifact = await tool._arun_impl()++ assert [task["id"] for task in artifact["tasks"]] == [str(visible.id)]+@parameterized_class(("filter_value", "should_match"),@@ -787,6 +858,17 @@ class TestListTaskRunsTool(BaseTaskToolTest):assert f"Run ID: {run.id}" in content+ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_list_runs_in_other_users_private_space(self):+ task, _run = await self._create_other_users_private_task()+ tool = self._create_tool(ListTaskRunsTool)++ content, artifact = await tool._arun_impl(task_id=str(task.id))++ assert "not found" in content+ assert artifact["error"] == "not_found"+@pytest.mark.django_db@pytest.mark.asyncioasync def test_list_runs_shows_error_truncated(self):diff --git a/products/tasks/backend/tests/test_slack_thread_context.py b/products/tasks/backend/tests/test_slack_thread_context.pyindex 21c52905cd02..ee73bc024cce 100644--- a/products/tasks/backend/tests/test_slack_thread_context.py+++ b/products/tasks/backend/tests/test_slack_thread_context.py@@ -96,6 +96,17 @@ class TestSlackThreadContextEndpoint(_SlackThreadContextBase):response = self.client.get(self._url("https://posthog.slack.com/archives/C0ACRAMJUAG/p1779956938619299"))assert response.status_code == status.HTTP_403_FORBIDDEN+ def test_other_project_member_cannot_resolve_private_slack_task(self):+ self._create_fixture()+ other_user = User.objects.create_user(email="[email protected]", first_name="Bob", password="password")+ self.organization.members.add(other_user)+ other_client = APIClient()+ other_client.force_authenticate(other_user)++ response = other_client.get(self._url("https://posthog.slack.com/archives/C0ACRAMJUAG/p1779956938619299"))++ assert response.status_code == status.HTTP_404_NOT_FOUND+def test_malformed_url_returns_400(self):response = self.client.get(self._url("https://posthog.slack.com/not/a/permalink"))assert response.status_code == status.HTTP_400_BAD_REQUEST@@ -113,6 +124,14 @@ class TestSlackThreadContextEndpoint(_SlackThreadContextBase):assert body["thread"]["channel"] == "C0ACRAMJUAG"assert body["thread"]["thread_ts"] == "1779956938.619299"+ def test_soft_deleted_task_has_no_slack_thread_context(self):+ task, _run, _mapping = self._create_fixture()+ task.soft_delete()++ response = self.client.get(self._url("https://posthog.slack.com/archives/C0ACRAMJUAG/p1779956938619299"))++ assert response.status_code == status.HTTP_404_NOT_FOUND+def test_happy_path_returns_task_and_runs(self):task, run, mapping = self._create_fixture()with patch(diff --git a/products/tasks/backend/visibility.py b/products/tasks/backend/visibility.pyindex ee14dce5cce9..cd04be73195d 100644--- a/products/tasks/backend/visibility.py+++ b/products/tasks/backend/visibility.py@@ -2,23 +2,15 @@Kept out of the API module so import-light consumers (the file-system registration inposthog.api.file_system.registrations, which loads at django.setup()) don't pull the whole-tasks API surface — its module-scope imports reach jsonschema and the modal SDK.+tasks API surface. Its module-scope imports reach jsonschema and the modal SDK."""from django.db.models import Qfrom products.tasks.backend.models import Channel, Task-# Origin products whose tasks are team-scoped rather than personal: every team member-# can view them regardless of who created them.-# - SIGNAL_REPORT / SIGNALS_SCOUT: pipeline artifacts attached to a system-picked-# `created_by` so the agent can mint an OAuth token, but they are not personal.-# - ONBOARDING: the "Set up PostHog" wizard task. Its `created_by` is the real person who-# went through onboarding (not a system pick), but we surface it team-wide so anyone on-# the team can see and pick up the setup, not just whoever happened to start it.-# - HOGDESK: support-desk Code threads. The task is pinned to the support ticket via a-# shared ticket tag, so any agent opening the ticket resumes the same thread — it must-# be viewable by the whole team, not just the agent who started it.+# These origins predate channels and remain team-scoped while their tasks have no channel.+# Once a task is filed into a channel, the channel is authoritative.TEAM_VISIBLE_ORIGIN_PRODUCTS = [Task.OriginProduct.SIGNAL_REPORT,Task.OriginProduct.SIGNALS_SCOUT,@@ -26,58 +18,48 @@ TEAM_VISIBLE_ORIGIN_PRODUCTS = [Task.OriginProduct.HOGDESK,]-# Origin products whose tasks are team-readable but stay creator-driven, like-# public-channel tasks: teammates can open the task and read what the agent did or-# asked, but runs execute with the creator's credentials (oauth.py mints tokens from-# `task.created_by`), so edits, runs, and agent commands stay with the creator.-# - EXPERIMENTS: flag-cleanup tasks opened when an experiment ends. The experiment-# (and the task's status on it) is team-visible, so any team member should be able-# to open the task, not just whoever clicked "End experiment".TEAM_READABLE_ORIGIN_PRODUCTS = [*TEAM_VISIBLE_ORIGIN_PRODUCTS,Task.OriginProduct.EXPERIMENTS,]-def task_control_q(user_id: int | None) -> Q:- """Filter for tasks the given user may mutate or drive (edits, runs, agent commands).+def _creator_q(user_id: int | None) -> Q:+ return Q(pk__in=[]) if user_id is None else Q(created_by_id=user_id)+- A task is controllable if:- - its creator matches `user_id`, or- - it has no creator at all (legacy unowned tasks remain visible to any- team member — they cannot be executed in any case because oauth.py- requires `task.created_by` to mint OAuth tokens), or- - its `origin_product` is one of `TEAM_VISIBLE_ORIGIN_PRODUCTS`, i.e. a- team-scoped artifact (signals, onboarding) any team member may pick up.+def task_control_q(user_id: int | None) -> Q:+ """Tasks the user may mutate or drive.- Deliberately narrower than ``task_visibility_q``: public-channel tasks are- team-readable but stay creator-driven — seeing a teammate's task in a feed- must not allow editing it, starting runs, or messaging its agent (thread- forwarding is the explicit, author-only path for that).+ A task with a channel must be visible through that channel and owned by the user.+ Null-channel tasks keep the product-origin control rules used before channels."""- return Q(created_by_id=user_id) | Q(created_by__isnull=True) | Q(origin_product__in=TEAM_VISIBLE_ORIGIN_PRODUCTS)+ channeled_q = Q(channel_id__isnull=False) & Channel.visible_to_q(user_id, relation="channel") & _creator_q(user_id)+ legacy_q = Q(channel_id__isnull=True) & (+ _creator_q(user_id) | Q(created_by__isnull=True) | Q(origin_product__in=TEAM_VISIBLE_ORIGIN_PRODUCTS)+ )+ return channeled_q | legacy_qdef task_visibility_q(user_id: int | None) -> Q:- """Filter for tasks visible (readable) to the given user.+ """Tasks readable by the user.- Everything controllable per ``task_control_q``, plus team-readable origins- and tasks in a public channel: channel feeds are multiplayer, so every team- member sees every task filed there. Personal-channel ("#me") tasks stay- creator-only via the control rules.+ Channel visibility is authoritative when a task has a channel. The creator and+ product-origin fallback applies only to null-channel compatibility rows."""- return (- task_control_q(user_id)- | Q(origin_product__in=TEAM_READABLE_ORIGIN_PRODUCTS)- | Q(channel__channel_type=Channel.ChannelType.PUBLIC, channel__deleted=False)+ channeled_q = Q(channel_id__isnull=False) & Channel.visible_to_q(user_id, relation="channel")+ legacy_q = Q(channel_id__isnull=True) & (+ _creator_q(user_id) | Q(created_by__isnull=True) | Q(origin_product__in=TEAM_READABLE_ORIGIN_PRODUCTS))+ return channeled_q | legacy_qdef task_run_visibility_q(user_id: int | None) -> Q:- """`task_visibility_q` traversed via the `task` FK on TaskRun / TaskAutomation."""- return (- Q(task__created_by_id=user_id)+ """``task_visibility_q`` traversed through the parent task relation."""+ channeled_q = Q(task__channel_id__isnull=False) & Channel.visible_to_q(user_id, relation="task__channel")+ legacy_q = Q(task__channel_id__isnull=True) & (+ (Q(task__pk__in=[]) if user_id is None else Q(task__created_by_id=user_id))| Q(task__created_by__isnull=True)| Q(task__origin_product__in=TEAM_READABLE_ORIGIN_PRODUCTS)- | Q(task__channel__channel_type=Channel.ChannelType.PUBLIC, task__channel__deleted=False))+ return channeled_q | legacy_qdiff --git a/products/tasks/docs/CHANNELS.md b/products/tasks/docs/CHANNELS.mdindex 0f3c1d8bf669..3b678a78782c 100644--- a/products/tasks/docs/CHANNELS.md+++ b/products/tasks/docs/CHANNELS.md@@ -1,9 +1,11 @@# Channels & Threads (PostHog Desktop / Bluebird)-Spec for the Slack-style channel revamp. A channel is a shared feed where each-member message kicks off a task; the task renders as a card everyone in the-channel can see. Every task is owned by a channel. Each task has one thread — a-side-chain of human messages that never reach the agent unless the task author+A channel is the backend model for a space. Public spaces are visible to project members.+`#me` is a private space that only its owner can access. A task with a channel inherits+that channel's visibility. Null-channel tasks keep the legacy creator and product-origin+rules until their product adopts spaces.++Each task has one thread. Human messages reach the agent only when the task authorexplicitly forwards one.## Django models@@ -42,7 +44,7 @@ class Channel(models.Model):class Task(...):- # every new task is owned by the channel it was kicked off in; legacy tasks stay NULL+ # Ordinary user tasks get a channel; legacy and product tasks can remain NULL.channel = models.ForeignKey("tasks.Channel", on_delete=models.SET_NULL, null=True, blank=True, related_name="tasks", db_index=False)@@ -71,10 +73,16 @@ class TaskThreadMessage(models.Model):### Visibility-`task_visibility_q` gains `| Q(channel__channel_type=PUBLIC)`: a task filed to a-public channel is visible to every team member (multiplayer feed). Tasks in a-personal channel remain visible only via the existing `created_by` rule.-Thread messages inherit the task's visibility.+A task with a channel uses only channel visibility:++- `PUBLIC` is readable by project members.+- `PERSONAL` is readable only by `Channel.created_by` and is shown as a private space.+- Task origin and creator fallbacks never widen a task with a channel.++A null-channel task uses the legacy creator and team-readable origin rules. Thread+messages, runs, artifacts, conversations, and task activity inherit task visibility.+A future selected-member private space can extend `Channel.visible_to_q` with channel+membership without adding permissions to Task.## API@@ -85,16 +93,24 @@ Thread messages inherit the task's visibility.so every user always has one.- `POST / {name}` — resolve-or-create a public channel by name(`get_or_create`, so concurrent creates and name-bridging are race-safe).-- `PATCH /{id}/ {name}` — rename a public channel. Personal channels cannot be renamed.-- `DELETE /{id}/` — soft-delete a public channel. Personal channels cannot be deleted.+- `PATCH /{id}/ {name}` - any project member can rename or configure a public channel. Private `#me` spaces cannot be renamed.+- `DELETE /{id}/` - any project member can delete an empty public channel. Private `#me` and non-empty spaces cannot be deleted.### Task endpoints-- `TaskWriteSerializer` accepts `channel` (UUID). Must belong to the team; a- personal channel is only accepted from its owner.+- `TaskCreateSerializer` accepts `channel` (UUID). It must belong to the team. A+ private `#me` space is accepted only from its owner.+- Omitting `channel` for an ordinary user task files it into the user's `#me` space.+- A task controller can move a task by updating `channel` to a public or owned private space. Existing callers can still clear `channel` for legacy compatibility.- `TaskSerializer` / `TaskDetailDTO` emit `channel`.- `GET /tasks/?channel=<uuid>` filters the list to a channel's feed.+### Canvas endpoints++- Project members can create and read Canvases in public channels.+- Only a Canvas creator can change Canvas metadata or source.+- Any project member can queue a build for the current source version through `publish-current-version`.+### `/api/projects/{id}/tasks/{task_id}/thread_messages/`- `GET /` — thread messages, ascending `created_at` (paginated).@@ -128,6 +144,6 @@ Thread messages inherit the task's visibility.## Out of scope (v1)-- Channel membership / invited private channels (only team-public + personal).+- Selected-member private spaces and channel membership.- Message editing and emoji reactions.- Real-time push for feed/thread updates (clients poll; SSE can come later).diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.tsindex f0b45478ee86..9d201d25ba1f 100644--- a/products/tasks/frontend/generated/api.schemas.ts+++ b/products/tasks/frontend/generated/api.schemas.ts@@ -1268,6 +1268,11 @@ export interface PatchedChannelUpdateApi {repositories?: string[]}+export interface ChannelDeleteConflictApi {+ /** Why the space cannot be deleted. */+ detail: string+}+/*** The task currently generating this channel's CONTEXT.md, or null.*/@@ -4249,7 +4254,7 @@ export type TaskMentionsListParams = {export type TasksListParams = {/**- * Staff-only. When true, list every task on the team regardless of creator or channel, bypassing the per-user visibility filter. Ignored for non-staff users.+ * Local development only. With ph_debug=true, list all project tasks for debugging. Ignored outside local development.*/all_team_tasks?: boolean/**diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex b9b1fbe1b7fa..808563faff54 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -1108,6 +1108,20 @@"readOnlyHint": false}},+ "canvas-publish-current-version": {+ "description": "Queue a build for the canvas's current source version without changing its source or metadata. Any project member can use this in a public space. Pass the current_version_id read from canvas-source-retrieve. A stale value returns a 409 version_conflict.",+ "category": "Canvas",+ "feature": "canvas",+ "summary": "Publish current canvas version",+ "title": "Publish current canvas version",+ "required_scopes": ["canvas:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"canvas-source-retrieve": {"description": "Read a canvas's source project and its `current_version_id`. Always call this before editing a canvas: edit the returned files, then publish the complete project with canvas-publish-create, passing the `current_version_id` you read as `expected_current_version_id` so concurrent edits are not overwritten. Canvases that predate multi-file projects are presented as a synthetic project whose `src/canvas.tsx` holds the React component.","category": "Canvas",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex fa163a3433c7..451d3e18ee57 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -1123,6 +1123,20 @@"readOnlyHint": false}},+ "canvas-publish-current-version": {+ "description": "Queue a build for the canvas's current source version without changing its source or metadata. Any project member can use this in a public space. Pass the current_version_id read from canvas-source-retrieve. A stale value returns a 409 version_conflict.",+ "category": "Canvas",+ "feature": "canvas",+ "summary": "Publish current canvas version",+ "title": "Publish current canvas version",+ "required_scopes": ["canvas:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"canvas-source-retrieve": {"description": "Read a canvas's source project and its `current_version_id`. Always call this before editing a canvas: edit the returned files, then publish the complete project with canvas-publish-create, passing the `current_version_id` you read as `expected_current_version_id` so concurrent edits are not overwritten. Canvases that predate multi-file projects are presented as a synthetic project whose `src/canvas.tsx` holds the React component.","category": "Canvas",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 44b526f0a3da..ffb0eb46088c 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -14378,6 +14378,11 @@ export namespace Schemas {current_version_id: string | null;}+ export interface CanvasPublishCurrentVersion {+ /** Current source version to publish. A changed head returns a 409 version_conflict. */+ expected_current_version_id: string;+ }+/*** Payload for reverting the canvas's head to an existing source version.*/@@ -14982,6 +14987,11 @@ export namespace Schemas {starred?: boolean;}+ export interface ChannelDeleteConflict {+ /** Why the space cannot be deleted. */+ detail: string;+ }+/*** * `slack_channel_message` - Channel message* * `slack_bot_mention` - Bot mention@@ -16587,10 +16597,7 @@ export namespace Schemas {/*** Conversation envelope variant: ``latest_run`` is just the latest run's id, not the nested* run detail. The frontend only needs the id to reconnect to sandbox logs, and emitting the id- * avoids presigning a log URL per conversation.- *- * Read access here follows the conversation (the share-by-link unit), not per-creator task- * visibility — write/send stays creator-gated. See ``tasks_facade.get_conversation_task_dtos``.+ * avoids presigning a log URL per conversation. Task data follows the task's space visibility.*/export interface ConversationTask {id: string;@@ -88811,7 +88818,7 @@ export namespace Schemas {export type TasksListParams = {/**- * Staff-only. When true, list every task on the team regardless of creator or channel, bypassing the per-user visibility filter. Ignored for non-staff users.+ * Local development only. With ph_debug=true, list all project tasks for debugging. Ignored outside local development.*/all_team_tasks?: boolean;/**diff --git a/services/mcp/src/generated/canvas/api.ts b/services/mcp/src/generated/canvas/api.tsindex 64f303f03c4c..538dc6154ddc 100644--- a/services/mcp/src/generated/canvas/api.ts+++ b/services/mcp/src/generated/canvas/api.ts@@ -3,7 +3,7 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 10 enabled ops+ * PostHog API - MCP 11 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -447,6 +447,24 @@ export const CanvasesPublishCreateBody = /* @__PURE__ */ zod}).describe('Payload for publishing a complete canvas source project.')+/**+ * Queue a build for the current source version without changing source or metadata.+ */+export const CanvasesPublishCurrentVersionCreateParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe('A UUID string identifying this canvas.'),+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++export const CanvasesPublishCurrentVersionCreateBody = /* @__PURE__ */ zod.object({+ expected_current_version_id: zod+ .string()+ .describe('Current source version to publish. A changed head returns a 409 version_conflict.'),+})+/*** Read the canvas's source project and its `current_version_id`.*diff --git a/services/mcp/src/generated/tasks/api.ts b/services/mcp/src/generated/tasks/api.tsindex e75a3c2f420f..616dbb937907 100644--- a/services/mcp/src/generated/tasks/api.ts+++ b/services/mcp/src/generated/tasks/api.ts@@ -867,7 +867,7 @@ export const TasksListQueryParams = /* @__PURE__ */ zod.object({.boolean().default(tasksListQueryAllTeamTasksDefault).describe(- 'Staff-only. When true, list every task on the team regardless of creator or channel, bypassing the per-user visibility filter. Ignored for non-staff users.'+ 'Local development only. With ph_debug=true, list all project tasks for debugging. Ignored outside local development.'),archived: zod.enum(['true', 'false', 'all'])diff --git a/services/mcp/src/tools/generated/canvas.ts b/services/mcp/src/tools/generated/canvas.tsindex a9a46d1752ad..75f9ed59c590 100644--- a/services/mcp/src/tools/generated/canvas.ts+++ b/services/mcp/src/tools/generated/canvas.ts@@ -17,6 +17,8 @@ import {CanvasesPromoteCreateParams,CanvasesPublishCreateBody,CanvasesPublishCreateParams,+ CanvasesPublishCurrentVersionCreateBody,+ CanvasesPublishCurrentVersionCreateParams,CanvasesSourceRetrieveParams,CanvasesSourceRetrieveQueryParams,CanvasesValidateCreateBody,@@ -229,6 +231,28 @@ const canvasPublishCreate = (): ToolBase<typeof CanvasPublishCreateSchema, Schem},})+const CanvasPublishCurrentVersionSchema = CanvasesPublishCurrentVersionCreateParams.omit({ project_id: true }).extend(+ CanvasesPublishCurrentVersionCreateBody.shape+)++const canvasPublishCurrentVersion = (): ToolBase<typeof CanvasPublishCurrentVersionSchema, Schemas.CanvasBuild> => ({+ name: 'canvas-publish-current-version',+ schema: CanvasPublishCurrentVersionSchema,+ handler: async (context: Context, params: z.infer<typeof CanvasPublishCurrentVersionSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.expected_current_version_id !== undefined) {+ body['expected_current_version_id'] = params.expected_current_version_id+ }+ const result = await context.api.request<Schemas.CanvasBuild>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/canvases/${encodeURIComponent(String(params.id))}/publish-current-version/`,+ body,+ })+ return result+ },+})+const CanvasSourceRetrieveSchema = CanvasesSourceRetrieveParams.omit({ project_id: true }).extend(CanvasesSourceRetrieveQueryParams.shape).extend({ id: CanvasesSourceRetrieveParams.shape['id'].describe('ID of the canvas whose source to read.') })@@ -280,6 +304,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'canvas-list': canvasList,'canvas-promote-create': canvasPromoteCreate,'canvas-publish-create': canvasPublishCreate,+ 'canvas-publish-current-version': canvasPublishCurrentVersion,'canvas-source-retrieve': canvasSourceRetrieve,'canvas-validate-create': canvasValidateCreate,}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-publish-current-version.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-publish-current-version.jsonnew file mode 100644index 000000000000..e4b77c357d57--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-publish-current-version.json@@ -0,0 +1,15 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "expected_current_version_id": {+ "description": "Current source version to publish. A changed head returns a 409 version_conflict.",+ "type": "string"+ },+ "id": {+ "description": "A UUID string identifying this canvas.",+ "type": "string"+ }+ },+ "required": ["id", "expected_current_version_id"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-list.jsonindex 84dde240b709..fe1f95e894d2 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-list.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-list.json@@ -3,7 +3,7 @@"properties": {"all_team_tasks": {"default": false,- "description": "Staff-only. When true, list every task on the team regardless of creator or channel, bypassing the per-user visibility filter. Ignored for non-staff users.",+ "description": "Local development only. With ph_debug=true, list all project tasks for debugging. Ignored outside local development.","type": "boolean"},"archived": {