: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): return canvas urls in API responses and name the task's channel in the space 403 (#82550)
Peter Kirkhambbc6f4bf597f
diff --git a/products/canvas/backend/presentation/serializers.py b/products/canvas/backend/presentation/serializers.pyindex ef7755b89713..303ba3e64e93 100644--- a/products/canvas/backend/presentation/serializers.py+++ b/products/canvas/backend/presentation/serializers.py@@ -1,5 +1,7 @@from typing import Any+from django.conf import settings+from rest_framework import serializersfrom posthog.api.shared import UserBasicSerializer@@ -11,6 +13,17 @@ from products.canvas.backend.models import Canvas# from the contract's total-source cap rather than restating the number._MAX_ASSET_BASE64_LENGTH = (contract_limits()["maxSourceTotalBytes"] + 2) // 3 * 4+_CANVAS_URL_HELP_TEXT = (+ "Canonical link to the canvas in the PostHog app. The only valid way to link to a canvas — "+ "share this when pointing a user at it; never construct a canvas URL."+)+++def canvas_url(canvas: Canvas) -> str:+ # The same shape the thread-message announcements use; the route deep-links+ # into the desktop app and renders in the web app.+ return f"{settings.SITE_URL}/code/canvas/{canvas.channel_id}/{canvas.id}"+class CanvasSerializer(serializers.ModelSerializer):"""A canvas document. Version/build content hangs off the source and build endpoints."""@@ -29,6 +42,7 @@ class CanvasSerializer(serializers.ModelSerializer):)created_by = UserBasicSerializer(read_only=True)pinned = serializers.SerializerMethodField(help_text="Whether the canvas is pinned to its channel.")+ url = serializers.SerializerMethodField(help_text=_CANVAS_URL_HELP_TEXT)class Meta:model = Canvas@@ -46,12 +60,16 @@ class CanvasSerializer(serializers.ModelSerializer):"created_by","created_at","updated_at",+ "url",]read_only_fields = fieldsdef get_pinned(self, canvas: Canvas) -> bool:return canvas.pinned_at is not None+ def get_url(self, canvas: Canvas) -> str:+ return canvas_url(canvas)+class CanvasCreateSerializer(serializers.Serializer):"""Payload for creating a new, empty canvas in a channel."""@@ -209,6 +227,10 @@ class CanvasSummarySerializer(serializers.Serializer):help_text="Id of the canvas's live (last successful, still-eligible) build. Null until a build completes.",)created_at = serializers.DateTimeField(help_text="When the canvas was created.")+ url = serializers.SerializerMethodField(help_text=_CANVAS_URL_HELP_TEXT)++ def get_url(self, canvas: Canvas) -> str:+ return canvas_url(canvas)class CanvasVersionSerializer(serializers.Serializer):diff --git a/products/canvas/backend/presentation/views.py b/products/canvas/backend/presentation/views.pyindex 9aa1bf5d147e..ecf0c659fe0c 100644--- a/products/canvas/backend/presentation/views.py+++ b/products/canvas/backend/presentation/views.py@@ -1,7 +1,6 @@from typing import Any, castfrom uuid import UUID-from django.conf import settingsfrom django.core.exceptions import ValidationError as DjangoValidationErrorfrom django.db.models import Q, QuerySetfrom django.utils import timezone@@ -48,6 +47,7 @@ from products.canvas.backend.presentation.serializers import (CanvasValidateRequestSerializer,CanvasValidateResponseSerializer,CanvasVersionSerializer,+ canvas_url,)from products.canvas.backend.source import apply_source_edits, has_errors, validate_source_projectfrom products.tasks.backend.facade import api as tasks_facade@@ -197,13 +197,16 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):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,- )+ if self._is_sandbox_authenticated(request):+ task_channel_id = tasks_facade.task_channel_id(sandbox_task_id, self.team_id) if sandbox_task_id else None+ if task_channel_id != channel_id:+ # Naming the right channel lets the agent recover in one step+ # and tell the user where the canvas will actually land.+ hint = f' Use the task\'s channel "{task_channel_id}".' if task_channel_id else ""+ return Response(+ {"detail": f"This sandbox can create canvases only in its task's space.{hint}"},+ status=status.HTTP_403_FORBIDDEN,+ )canvas = Canvas.objects.create(team_id=self.team_id,channel_id=channel_id,@@ -894,7 +897,7 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):self.team_id,acting_user_id=user.id if user else None,canvas_name=canvas.name or "Canvas",- canvas_url=f"{settings.SITE_URL}/code/canvas/{canvas.channel_id}/{canvas.id}",+ canvas_url=canvas_url(canvas),)@staticmethoddiff --git a/products/canvas/backend/tests/test_canvas_api.py b/products/canvas/backend/tests/test_canvas_api.pyindex f6dddae7051d..38a97c82fd88 100644--- a/products/canvas/backend/tests/test_canvas_api.py+++ b/products/canvas/backend/tests/test_canvas_api.py@@ -220,10 +220,24 @@ class TestCanvasCrud(CanvasAPIBaseTest):format="json",HTTP_X_POSTHOG_TASK_ID=str(other_task.id),)+ with team_scope(self.team.id):+ other_channel = Channel.objects.create(team=self.team, name="elsewhere")+ wrong_channel = client.post(+ url,+ {"name": "Elsewhere canvas", "channel_id": str(other_channel.id)},+ format="json",+ HTTP_X_POSTHOG_TASK_ID=str(bound_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+ created = allowed.json()+ assert Canvas.objects.unscoped().get(id=created["id"]).generation_task_id == bound_task.id+ # The url is what agents hand to users; a guessed link does not resolve.+ assert created["url"].endswith(f"/code/canvas/{self.channel.id}/{created['id']}")assert denied.status_code == status.HTTP_403_FORBIDDEN+ assert wrong_channel.status_code == status.HTTP_403_FORBIDDEN+ # The rejection names the task's channel so the agent can recover in one step.+ assert str(self.channel.id) in wrong_channel.json()["detail"]def test_task_bound_sandbox_can_read_canvases_created_by_the_authenticated_user(self):bound_task = Task.objects.create(diff --git a/products/canvas/frontend/generated/api.schemas.ts b/products/canvas/frontend/generated/api.schemas.tsindex 701d51185961..62c7b725b3ec 100644--- a/products/canvas/frontend/generated/api.schemas.ts+++ b/products/canvas/frontend/generated/api.schemas.ts@@ -92,6 +92,8 @@ export interface CanvasApi {readonly created_by: UserBasicApireadonly created_at: stringreadonly updated_at: string+ /** Canonical link to the canvas in the PostHog app. The only valid way to link to a canvas — share this when pointing a user at it; never construct a canvas URL. */+ readonly url: string}export interface PaginatedCanvasListApi {@@ -566,6 +568,8 @@ export interface CanvasSummaryApi {published_build_id: string | null/** When the canvas was created. */created_at: string+ /** Canonical link to the canvas in the PostHog app. The only valid way to link to a canvas — share this when pointing a user at it; never construct a canvas URL. */+ readonly url: string}/**diff --git a/products/canvas/mcp/tools.yaml b/products/canvas/mcp/tools.yamlindex 30b6c1c29567..d1703e485969 100644--- a/products/canvas/mcp/tools.yaml+++ b/products/canvas/mcp/tools.yaml@@ -41,7 +41,8 @@ tools:description: >Create a new, empty canvas in a channel. Returns the canvas's id and (null) `current_version_id`; give itsource by publishing a project with canvas-publish-create. Only create a canvas when no existing one is the- intended target — list them with canvas-list first.+ intended target — list them with canvas-list first. The response's `url` is the canvas's only valid link —+ share it verbatim when pointing the user at the canvas; never construct a canvas URL yourself.param_overrides:channel_id:description:@@ -123,7 +124,8 @@ tools:title: List canvasesdescription: >List the project's canvases (newest first), optionally scoped to one channel via `channel`. Use this to- resolve which canvas a request refers to before reading or publishing source.+ resolve which canvas a request refers to before reading or publishing source. Each row's `url` is that+ canvas's only valid link — share it verbatim; never construct a canvas URL yourself.param_overrides:channel:description: Only return canvases in this channel (channel id).diff --git a/products/canvas/skills/building-canvases/SKILL.md b/products/canvas/skills/building-canvases/SKILL.mdindex 8a16387540f0..bf298cb1ecc0 100644--- a/products/canvas/skills/building-canvases/SKILL.md+++ b/products/canvas/skills/building-canvases/SKILL.md@@ -70,6 +70,11 @@ Save once per requested change, when the canvas is ready — not after every micstaged a draft, end your reply by saying a draft is ready to preview and promote; the`validating-and-publishing-canvases` skill covers the draft → build → preview → promote flow.+End your reply by naming the channel the canvas is in and linking it with the `url` field the+canvas tools return (`canvas-create`, `canvas-list`, and the publish/source responses carry it).+That field is the only valid link to a canvas — never construct one yourself; guessed URLs+(project pages, web routes) do not resolve.+## Source-project shape- Keep `index.html` as the entry shell returned by the source tool.diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 308fce532e1f..d8404ded1393 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -255,8 +255,8 @@ __all__ = ["soft_delete_task","start_task_run","task_accessible_for_run_view",+ "task_channel_id","task_exists",- "task_is_in_channel","task_ids_with_pr_url_subquery","task_run_has_slack_mapping","task_run_is_terminal",@@ -759,8 +759,9 @@ def task_exists(task_id: str | UUID, team_id: int) -> bool: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_channel_id(task_id: str | UUID, team_id: int) -> UUID | None:+ """The channel a (non-deleted) task is filed in, or None."""+ return Task.objects.filter(id=task_id, team_id=team_id, deleted=False).values_list("channel_id", flat=True).first()def task_owned_by_user(task_id: str | UUID, team_id: int, user_id: int) -> bool:diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex d546ec62d93c..afb0f7ebda7d 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -1011,7 +1011,7 @@}},"canvas-create": {- "description": "Create a new, empty canvas in a channel. Returns the canvas's id and (null) `current_version_id`; give it source by publishing a project with canvas-publish-create. Only create a canvas when no existing one is the intended target — list them with canvas-list first.",+ "description": "Create a new, empty canvas in a channel. Returns the canvas's id and (null) `current_version_id`; give it source by publishing a project with canvas-publish-create. Only create a canvas when no existing one is the intended target — list them with canvas-list first. The response's `url` is the canvas's only valid link — share it verbatim when pointing the user at the canvas; never construct a canvas URL yourself.","category": "Canvas","feature": "canvas","summary": "Create canvas",@@ -1067,7 +1067,7 @@}},"canvas-list": {- "description": "List the project's canvases (newest first), optionally scoped to one channel via `channel`. Use this to resolve which canvas a request refers to before reading or publishing source.",+ "description": "List the project's canvases (newest first), optionally scoped to one channel via `channel`. Use this to resolve which canvas a request refers to before reading or publishing source. Each row's `url` is that canvas's only valid link — share it verbatim; never construct a canvas URL yourself.","category": "Canvas","feature": "canvas","summary": "List canvases",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 8696b7e32051..8b04aea8ff64 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -1026,7 +1026,7 @@}},"canvas-create": {- "description": "Create a new, empty canvas in a channel. Returns the canvas's id and (null) `current_version_id`; give it source by publishing a project with canvas-publish-create. Only create a canvas when no existing one is the intended target — list them with canvas-list first.",+ "description": "Create a new, empty canvas in a channel. Returns the canvas's id and (null) `current_version_id`; give it source by publishing a project with canvas-publish-create. Only create a canvas when no existing one is the intended target — list them with canvas-list first. The response's `url` is the canvas's only valid link — share it verbatim when pointing the user at the canvas; never construct a canvas URL yourself.","category": "Canvas","feature": "canvas","summary": "Create canvas",@@ -1082,7 +1082,7 @@}},"canvas-list": {- "description": "List the project's canvases (newest first), optionally scoped to one channel via `channel`. Use this to resolve which canvas a request refers to before reading or publishing source.",+ "description": "List the project's canvases (newest first), optionally scoped to one channel via `channel`. Use this to resolve which canvas a request refers to before reading or publishing source. Each row's `url` is that canvas's only valid link — share it verbatim; never construct a canvas URL yourself.","category": "Canvas","feature": "canvas","summary": "List canvases",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 4afb739066ff..2c66ab214800 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -14268,6 +14268,8 @@ export namespace Schemas {readonly created_by: UserBasic;readonly created_at: string;readonly updated_at: string;+ /** Canonical link to the canvas in the PostHog app. The only valid way to link to a canvas — share this when pointing a user at it; never construct a canvas URL. */+ readonly url: string;}/**@@ -14746,6 +14748,8 @@ export namespace Schemas {published_build_id: string | null;/** When the canvas was created. */created_at: string;+ /** Canonical link to the canvas in the PostHog app. The only valid way to link to a canvas — share this when pointing a user at it; never construct a canvas URL. */+ readonly url: string;}/**