:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(canvas): start cloud tasks with space defaults (#98194)
Peter Kirkham469f9f7c53fd
diff --git a/products/canvas/backend/actions.py b/products/canvas/backend/actions.pyindex f51597f33b2a..831e610bf365 100644--- a/products/canvas/backend/actions.py+++ b/products/canvas/backend/actions.py@@ -22,12 +22,21 @@ from rest_framework import serializersfrom posthog.dataclasses import frozenif TYPE_CHECKING:+ from rest_framework.response import Response+from posthog.models import Teamfrom products.canvas.backend.models import Canvaslogger = structlog.get_logger(__name__)++class CanvasActionDenied(Exception):+ def __init__(self, response: "Response") -> None:+ super().__init__(str(response.data))+ self.response = response++# Kill switch: enabling this flag for a team turns every action verb off at# once. Evaluation failure leaves actions on — the switch is for emergencies,# not a gate normal traffic should wait on.@@ -70,6 +79,10 @@ class TaskCreatePayloadSerializer(serializers.Serializer):)+class TaskCreateAndRunPayloadSerializer(TaskCreatePayloadSerializer):+ idempotency_key = serializers.UUIDField(help_text="Reuse this UUID when retrying the same cloud task request.")++def _create_annotation(team_id: int, user_id: int, canvas: "Canvas", payload: dict[str, Any]) -> dict[str, Any]:from products.annotations.backend.facade import api as annotations_facade # noqa: PLC0415 — load on execute@@ -88,6 +101,31 @@ def _create_task(team_id: int, user_id: int, canvas: "Canvas", payload: dict[strreturn {"task_id": str(task_id)}+def _create_and_run_task(team_id: int, user_id: int, canvas: "Canvas", payload: dict[str, Any]) -> dict[str, Any]:+ from posthog.models.user import User # noqa: PLC0415++ from products.tasks.backend.facade.access import usage_limit_response # noqa: PLC0415+ from products.tasks.backend.facade.canvas_tasks import ( # noqa: PLC0415 - keeps task runtime imports off canvas validation+ create_and_run_channel_task,+ )++ def check_usage() -> None:+ if response := usage_limit_response(User.objects.get(id=user_id), team_id):+ raise CanvasActionDenied(response)++ run = create_and_run_channel_task(+ team_id,+ user_id,+ canvas.channel_id,+ canvas_id=canvas.id,+ title=payload["title"],+ description=payload["description"],+ idempotency_key=payload["idempotency_key"],+ before_create=check_usage,+ )+ return {"task_id": str(run.task_id), "run_id": str(run.id), "status": run.status}++@frozenclass CanvasAction:"""One verb of the registry: what it does, its payload shape, and how loudly the host must ask."""@@ -107,6 +145,7 @@ class CanvasAction:# warrants. Agents build against the deployed registry rather than a skill# file, so a verb's docs ship (and stay current) with the verb itself.usage: str+ starts_cloud_run: bool = FalseCANVAS_ACTIONS: dict[str, CanvasAction] = {@@ -145,5 +184,25 @@ CANVAS_ACTIONS: dict[str, CanvasAction] = {"not the canvas."),),+ CanvasAction(+ verb="tasks.create_and_run",+ summary="Create and start a cloud task in this space with default settings.",+ destructive=False,+ payload_serializer=TaskCreateAndRunPayloadSerializer,+ execute=_create_and_run_task,+ required_scopes=("task:write",),+ starts_cloud_run=True,+ usage=(+ "Payload `{title, description?, idempotency_key}` returns `{task_id, run_id, status}`. "+ "Creates a task in the canvas's space as the viewer and queues its cloud run. "+ "Inherits the space's repositories and the viewer's default run settings. "+ "The standard cloud access and usage limits apply. This action uses paid compute. "+ "Use a 'Start cloud task' button and disable it while the request is pending. "+ "Generate a UUID for idempotency_key once per intended task and reuse it on retries; "+ "a retry returns the existing task and latest run without starting another run. "+ "Use the returned status in the result message. A queued run has not finished. "+ "Declare this verb separately from tasks.create, which still creates a task without a run."+ ),+ ),]}diff --git a/products/canvas/backend/presentation/views.py b/products/canvas/backend/presentation/views.pyindex 2bf0acf848c0..b39963603139 100644--- a/products/canvas/backend/presentation/views.py+++ b/products/canvas/backend/presentation/views.py@@ -27,7 +27,7 @@ from posthog.storage.object_storage import ObjectStorageErrorfrom posthog.temporal.oauth import SANDBOX_OAUTH_APP_CLIENT_IDSfrom products.canvas.backend import build_service, error_reports-from products.canvas.backend.actions import CANVAS_ACTIONS, canvas_actions_disabled+from products.canvas.backend.actions import CANVAS_ACTIONS, CanvasActionDenied, canvas_actions_disabledfrom products.canvas.backend.capabilities import declared_actions, declared_connectors, declared_state_scopesfrom products.canvas.backend.contract import contract_limitsfrom products.canvas.backend.facade.api import (@@ -90,6 +90,7 @@ from products.canvas.backend.presentation.serializers import ()from products.canvas.backend.source import apply_source_edits, has_errors, validate_source_projectfrom products.tasks.backend.facade import api as tasks_facade+from products.tasks.backend.facade.access import code_access_required_responselogger = structlog.get_logger(__name__)@@ -1759,8 +1760,13 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.ModelViewSet):)verb_payload = entry.payload_serializer(data=payload.validated_data["payload"])verb_payload.is_valid(raise_exception=True)+ if entry.starts_cloud_run:+ if access_response := code_access_required_response(request, self.organization):+ return access_responsetry:result = entry.execute(self.team_id, user.id, canvas, verb_payload.validated_data)+ except CanvasActionDenied as error:+ return error.responseexcept ValueError as error:return Response({"detail": str(error)}, status=status.HTTP_400_BAD_REQUEST)# Every execution is audited: the trigger names the verb, the activitydiff --git a/products/canvas/backend/tests/test_canvas_api.py b/products/canvas/backend/tests/test_canvas_api.pyindex bc5aac84b6aa..3a30befdddbe 100644--- a/products/canvas/backend/tests/test_canvas_api.py+++ b/products/canvas/backend/tests/test_canvas_api.py@@ -1,4 +1,5 @@from datetime import timedelta+from types import SimpleNamespacefrom typing import Any, castfrom uuid import UUID, uuid4@@ -12,6 +13,7 @@ from parameterized import parameterizedfrom rest_framework import statusfrom rest_framework.test import APIClient+from posthog.models import Integrationfrom posthog.models.activity_logging.activity_log import ActivityLog, Detail, log_activityfrom posthog.models.oauth import OAuthAccessToken, OAuthApplicationfrom posthog.models.personal_api_key import PersonalAPIKey@@ -25,6 +27,8 @@ from products.canvas.backend import activity_visibility, build_servicefrom products.canvas.backend.actions import CANVAS_ACTIONS, TaskCreatePayloadSerializerfrom products.canvas.backend.models import Canvas, CanvasBuild, CanvasSourceVersionfrom products.canvas.backend.source import synthetic_source_project+from products.tasks.backend.facade.access import DesktopAccessDecision+from products.tasks.backend.facade.ai_run_defaults import update_team_ai_run_preferences, update_user_ai_run_preferencesfrom products.tasks.backend.facade.contracts import ComputeQuotaDenialReasonfrom products.tasks.backend.models import Channel, Task, TaskRun, TaskThreadMessage@@ -1929,12 +1933,13 @@ class TestCanvasActions(CanvasAPIBaseTest):@parameterized.expand([# canvas:write alone is not consent to write other resources.- ("canvas_scope_only", ["canvas:write"], status.HTTP_403_FORBIDDEN),- ("target_scope_held", ["canvas:write", "task:write"], status.HTTP_200_OK),+ ("canvas_scope_only", "tasks.create", ["canvas:write"], status.HTTP_403_FORBIDDEN),+ ("target_scope_held", "tasks.create", ["canvas:write", "task:write"], status.HTTP_200_OK),+ ("cloud_canvas_scope_only", "tasks.create_and_run", ["canvas:write"], status.HTTP_403_FORBIDDEN),])- def test_scoped_keys_need_the_verbs_target_scope(self, _name, scopes, expected_status):- canvas_id = self._actions_canvas()+ def test_scoped_keys_need_the_verbs_target_scope(self, _name, verb, scopes, expected_status):+ canvas_id = self._actions_canvas(verbs=(verb,))raw_key = generate_random_token_personal()PersonalAPIKey.objects.create(label="canvas-actions", user=self.user, secure_value=hash_key_value(raw_key), scopes=scopes@@ -1943,7 +1948,7 @@ class TestCanvasActions(CanvasAPIBaseTest):response = self.client.post(f"/api/projects/{self.team.id}/canvases/{canvas_id}/actions/invoke/",- {"verb": "tasks.create", "payload": {"title": "Scoped", "description": ""}},+ {"verb": verb, "payload": {"title": "Scoped", "description": "", "idempotency_key": str(uuid4())}},format="json",HTTP_AUTHORIZATION=f"Bearer {raw_key}",)@@ -1971,6 +1976,91 @@ class TestCanvasActions(CanvasAPIBaseTest):assert task.created_by_id == self.user.idassert task.channel_id == self.channel.idassert task.title == "Follow up"+ assert not task.runs.exists()++ @parameterized.expand([("without_repository", []), ("space_repositories", ["example/app", "example/api"])])+ def test_cloud_task_uses_space_and_viewer_defaults_once(self, _name: str, repositories: list[str]) -> None:+ canvas_id = self._actions_canvas(verbs=("tasks.create_and_run",))+ integration = Integration.objects.create(team=self.team, kind="github", config={})+ self.channel.repositories = repositories+ self.channel.github_integration = integration+ self.channel.save(update_fields=["repositories", "github_integration"])+ viewer = User.objects.create_and_join(self.organization, "[email protected]", None)+ update_team_ai_run_preferences(+ self.team.id,+ runtime_adapter="claude",+ model="claude-opus-4-8",+ reasoning_effort="high",+ )+ update_user_ai_run_preferences(+ self.team.id,+ viewer.id,+ runtime_adapter="codex",+ model="gpt-5.5",+ reasoning_effort="medium",+ )+ self.client.force_login(viewer)+ payload = {+ "title": "Review the signup flow",+ "description": "Check the empty state.",+ "idempotency_key": str(uuid4()),+ }++ with (+ patch(+ "products.tasks.backend.logic.services.code_usage_gate.get_desktop_access_decision",+ return_value=DesktopAccessDecision.ALLOWED,+ ),+ patch(+ "products.tasks.backend.logic.services.code_usage_gate.get_posthog_code_usage", return_value=None+ ) as usage,+ patch("products.tasks.backend.temporal.client.execute_task_processing_workflow") as dispatch,+ self.captureOnCommitCallbacks(execute=True),+ ):+ response = self._invoke(canvas_id, "tasks.create_and_run", payload)+ usage.return_value = SimpleNamespace(is_rate_limited=True, limit_type="burst", reset_at=None, is_pro=False)+ retry = self._invoke(canvas_id, "tasks.create_and_run", payload)+ new_request = self._invoke(canvas_id, "tasks.create_and_run", {**payload, "idempotency_key": str(uuid4())})++ assert response.status_code == status.HTTP_200_OK, response.json()+ assert retry.status_code == status.HTTP_200_OK, retry.json()+ assert response.json()["result"] == retry.json()["result"]+ assert new_request.status_code == status.HTTP_429_TOO_MANY_REQUESTS, new_request.json()+ task = Task.objects.get(id=response.json()["result"]["task_id"])+ run = task.runs.get(id=response.json()["result"]["run_id"])+ assert task.created_by_id == viewer.id+ assert task.channel_id == self.channel.id+ assert task.repositories == repositories+ assert task.github_integration_id == integration.id+ assert run.environment == TaskRun.Environment.CLOUD+ assert run.state["model"] == "gpt-5.5"+ assert run.state["runtime_adapter"] == "codex"+ assert run.state["reasoning_effort"] == "medium"+ assert task.runs.count() == 1+ dispatch.assert_called_once()++ @parameterized.expand([("access_denied", False, False, 403), ("usage_limited", True, True, 429)])+ def test_cloud_task_checks_access_and_usage_before_creating_work(+ self, _name: str, allowed: bool, limited: bool, expected_status: int+ ) -> None:+ canvas_id = self._actions_canvas(verbs=("tasks.create_and_run",))+ usage = SimpleNamespace(+ is_rate_limited=limited, limit_type="burst" if limited else None, reset_at=None, is_pro=False+ )+ with (+ patch(+ "products.tasks.backend.logic.services.code_usage_gate.get_desktop_access_decision",+ return_value=DesktopAccessDecision.ALLOWED if allowed else DesktopAccessDecision.STARTUP_PLAN,+ ),+ patch("products.tasks.backend.logic.services.code_usage_gate.get_posthog_code_usage", return_value=usage),+ ):+ response = self._invoke(+ canvas_id, "tasks.create_and_run", {"title": "Review", "idempotency_key": str(uuid4())}+ )++ assert response.status_code == expected_status, response.json()+ assert not Task.objects.exists()+ assert not TaskRun.objects.exists()def test_annotations_create_attributes_the_viewer(self):canvas_id = self._actions_canvas()@@ -1991,9 +2081,12 @@ class TestCanvasActions(CanvasAPIBaseTest):undeclared = self._invoke(canvas_id, "annotations.create", {"content": "x"})unknown = self._invoke(canvas_id, "flags.delete", {})+ cloud = self._invoke(canvas_id, "tasks.create_and_run", {"title": "Review", "idempotency_key": str(uuid4())})assert undeclared.status_code == status.HTTP_403_FORBIDDENassert unknown.status_code == status.HTTP_400_BAD_REQUEST+ assert cloud.status_code == status.HTTP_403_FORBIDDEN+ assert not Task.objects.exists()assert Annotation.objects.count() == 0def test_kill_switch_refuses_every_verb(self):diff --git a/products/tasks/backend/facade/canvas_tasks.py b/products/tasks/backend/facade/canvas_tasks.pynew file mode 100644index 000000000000..c0420eeb4cb5--- /dev/null+++ b/products/tasks/backend/facade/canvas_tasks.py@@ -0,0 +1,65 @@+from collections.abc import Callable+from uuid import UUID++from django.db import transaction++from products.tasks.backend.facade import api+from products.tasks.backend.facade.contracts import TaskRunDTO+from products.tasks.backend.models import Channel, Task+++def create_and_run_channel_task(+ team_id: int,+ user_id: int,+ channel_id: UUID,+ *,+ canvas_id: UUID,+ title: str,+ description: str,+ idempotency_key: UUID,+ before_create: Callable[[], None],+) -> TaskRunDTO:+ with transaction.atomic():+ channel = (+ Channel.objects.for_team(team_id)+ .select_for_update(of=("self",))+ .filter(Channel.visible_to_q(user_id), id=channel_id)+ .first()+ )+ if channel is None:+ raise ValueError("Space not found.")++ origin_key = f"canvas:{canvas_id}:{user_id}:{idempotency_key}"+ existing = Task.objects.filter(team_id=team_id, origin_key=origin_key).first()+ if existing is not None:+ if existing.deleted or existing.channel_id != channel.id or existing.created_by_id != user_id:+ raise ValueError("The previous task is no longer available. Start a new request.")+ latest_run = existing.latest_run+ if latest_run is None:+ raise ValueError("The previous task has no run. Open the task to start work.")+ run_id = latest_run.id+ else:+ before_create()+ task = api.create_task(+ team_id,+ user_id,+ validated_data={+ "title": title,+ "description": description,+ "channel": channel,+ "origin_key": origin_key,+ },+ )+ result = api.run_task(task.id, team_id, user_id, validated_data={})+ if result is None:+ raise ValueError("The task is no longer available.")+ if result.error is not None:+ raise ValueError(result.error.detail)+ if result.task is None or result.task.latest_run is None:+ raise ValueError("The cloud run could not be created. Try again.")+ run_id = result.task.latest_run.id++ run = api.get_task_run(run_id, team_id)+ if run is None:+ raise ValueError("The cloud run is no longer available.")+ return run