: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): stage draft builds before publishing (#80408)
Peter Kirkhama5a993b06c71
diff --git a/products/canvas/backend/build_service.py b/products/canvas/backend/build_service.pyindex 6614b66ecdf9..1277e355c0ba 100644--- a/products/canvas/backend/build_service.py+++ b/products/canvas/backend/build_service.py@@ -42,6 +42,7 @@ from posthog.models.user import Userfrom posthog.ph_client import ph_background_capturefrom posthog.storage import object_storage+from products.canvas.backend.capabilities import CapabilityWidening, capability_wideningfrom products.canvas.backend.contract import CANVAS_BUILDER_DIR, contract_limitsfrom products.canvas.backend.models import Canvas, CanvasBuild, CanvasSourceVersionfrom products.canvas.backend.source import (@@ -336,21 +337,30 @@ def _assert_build_capacity(team_id: int) -> None:raise CanvasBuildCapacityExceeded-def _claim_canvas_head(canvas: Canvas, *, has_expected_version: bool, expected_version_id: str | UUID | None) -> Canvas:+def _claim_canvas_head(+ canvas: Canvas,+ *,+ has_expected_version: bool,+ expected_version_id: str | UUID | None,+ check_capacity: bool = True,+) -> Canvas:"""Lock the canvas row and claim the right to advance its head.- Enforces the optimistic-version guard and the team build-capacity cap- under the row lock plus the team advisory lock. Must run inside a- transaction; returns the locked row. Raises CanvasVersionConflict or- CanvasBuildCapacityExceeded.+ Enforces the optimistic-version guard under the row lock, and (unless+ check_capacity is False) the team build-capacity cap under the team advisory+ lock. Promote passes check_capacity=False so adopting an already-built draft+ can't be blocked by the cap; it enforces capacity itself on the rebuild path.+ Must run inside a transaction; returns the locked row. Raises+ CanvasVersionConflict or CanvasBuildCapacityExceeded."""locked = Canvas.objects.for_team(canvas.team_id).select_for_update().get(pk=canvas.pk)current_id = str(locked.current_source_version_id) if locked.current_source_version_id else Noneexpected = str(expected_version_id) if expected_version_id else Noneif has_expected_version and current_id != expected:raise CanvasVersionConflict(current_id)- _lock_team_build_capacity(locked.team_id)- _assert_build_capacity(locked.team_id)+ if check_capacity:+ _lock_team_build_capacity(locked.team_id)+ _assert_build_capacity(locked.team_id)return locked@@ -482,28 +492,11 @@ def publish_source_project(canvas.save(update_fields=update_fields)# The pre-publish capabilities come from the parent version the claim- # recorded under the head lock — exact even against a concurrent publish,- # unlike a read taken before the transaction. None means "predates the- # snapshot", not "empty".- previous_capabilities = (- CanvasSourceVersion.objects.for_team(canvas.team_id)- .filter(pk=version.parent_version_id)- .values_list("capabilities", flat=True)- .first()- if version.parent_version_id- else None+ # recorded under the head lock, so the diff is exact even against a+ # concurrent publish.+ changes = _capabilities_changes(+ _version_capabilities(canvas.team_id, version.parent_version_id), version.capabilities)- changes = None- if previous_capabilities != version.capabilities:- changes = [- Change(- type="Canvas",- action="changed",- field="capabilities",- before=previous_capabilities,- after=version.capabilities,- )- ]_log_canvas_activity(canvas,user=created_by,@@ -523,15 +516,20 @@ def revert_to_version(user: User | None = None,was_impersonated: bool = False,) -> tuple[Canvas, CanvasBuild]:- """Move the canvas's head back to an existing version and rebuild it.+ """Move the canvas's head back to an existing published version and rebuild it.- Raises CanvasSourceVersion.DoesNotExist for a version that isn't this- canvas's, and CanvasBuildCapacityExceeded when the team cap is reached.+ Drafts are not revertable: a draft reaches the head only through+ promote_draft_version, which surfaces its capability widening first.+ Raises CanvasSourceVersion.DoesNotExist for a version that isn't one of this+ canvas's published versions, and CanvasBuildCapacityExceeded when the team+ cap is reached."""with transaction.atomic(), team_scope(canvas.team_id):canvas = _claim_canvas_head(canvas, has_expected_version=True, expected_version_id=expected_current_version_id)previous_head_id = str(canvas.current_source_version_id) if canvas.current_source_version_id else None- version = CanvasSourceVersion.objects.for_team(canvas.team_id).get(pk=version_id, canvas_id=canvas.id)+ version = CanvasSourceVersion.objects.for_team(canvas.team_id).get(+ pk=version_id, canvas_id=canvas.id, draft=False+ )canvas.current_source_version = versioncanvas.save(update_fields=["current_source_version", "updated_at"])build = _queue_build(version)@@ -556,6 +554,142 @@ def revert_to_version(return canvas, build+def create_draft_version(+ canvas: Canvas,+ *,+ project: dict[str, Any],+ prompt: str | None,+ task_id: UUID | None,+ created_by: User | None,+ was_impersonated: bool = False,+) -> tuple[CanvasSourceVersion, CanvasBuild, CapabilityWidening]:+ """Stage a validated project as a draft version and build it, without moving the head.++ A draft is a regular `CanvasSourceVersion` (same storage, history, and build+ pipeline) that is not the canvas head, so `_finalize_ready` never advances the+ live pointer to its build. Promote it with `promote_draft_version`. No version+ guard applies: a draft conflicts with nothing because it publishes nothing.+ Returns the widening of the draft's declared capabilities over the current+ head's, so callers can surface manifest growth before anything ships. Raises+ CanvasBuildCapacityExceeded or ObjectStorageError.+ """+ # Lock-free fail-fast, mirroring publish: reject a doomed draft before+ # paying for the upload. The commit transaction re-checks authoritatively+ # under the locks in _claim_canvas_head.+ with team_scope(canvas.team_id):+ _assert_build_capacity(canvas.team_id)++ key, digest, size = upload_source_project(canvas.team_id, canvas.id, project)+ with transaction.atomic(), team_scope(canvas.team_id):+ canvas = _claim_canvas_head(canvas, has_expected_version=False, expected_version_id=None)+ version = CanvasSourceVersion.objects.create(+ team_id=canvas.team_id,+ canvas=canvas,+ draft=True,+ parent_version_id=canvas.current_source_version_id,+ source_hash=digest,+ source_object_key=key,+ source_size=size,+ task_id=task_id,+ prompt=prompt or None,+ created_by=created_by,+ capabilities=project.get("capabilities") or {},+ )+ build = _queue_build(version)++ head_capabilities = _version_capabilities(canvas.team_id, version.parent_version_id)+ _log_canvas_activity(+ canvas,+ user=created_by,+ was_impersonated=was_impersonated,+ activity="drafted",+ detail=Detail(name=canvas.name, changes=_capabilities_changes(head_capabilities, version.capabilities)),+ )+ return version, build, capability_widening(head_capabilities, version.capabilities)+++def promote_draft_version(+ canvas: Canvas,+ version_id: str | UUID,+ expected_current_version_id: str | UUID | None,+ *,+ user: User | None = None,+ was_impersonated: bool = False,+) -> tuple[Canvas, CanvasBuild]:+ """Make a draft version the canvas head, adopting its build when one exists.++ A ready build whose artifacts have not been pruned by the retention sweep goes+ live directly with no rebuild. A build still in flight is adopted as-is — the+ version is the head by the time it finalizes, so _finalize_ready advances the+ live pointer; queuing another would double the work (and _queue_build only+ supersedes queued builds, not building ones). Only when no usable build exists+ (failed, or pruned) is a fresh one queued, which is why the capacity cap is+ only checked on that path. The version guard is required, like revert: a+ successful promote proves the caller saw the head it replaced. Raises+ CanvasSourceVersion.DoesNotExist for a version that isn't one of this canvas's+ drafts, CanvasVersionConflict, and CanvasBuildCapacityExceeded (rebuilds only).+ """+ with transaction.atomic(), team_scope(canvas.team_id):+ # Same head guard as revert; capacity is only enforced on the rebuild+ # path below, so adopting a surviving build can't hit the cap.+ canvas = _claim_canvas_head(+ canvas, has_expected_version=True, expected_version_id=expected_current_version_id, check_capacity=False+ )+ previous_head_id = canvas.current_source_version_id+ version = CanvasSourceVersion.objects.for_team(canvas.team_id).get(+ pk=version_id, canvas_id=canvas.id, draft=True+ )+ version.draft = False+ version.save(update_fields=["draft"])+ canvas.current_source_version = version+ update_fields = ["current_source_version", "updated_at"]+ build = (+ version.builds.filter(status=CanvasBuild.STATUS_READY, artifact_object_prefix__isnull=False)+ .order_by("-created_at")+ .first()+ )+ if build is not None:+ canvas.published_build = build+ update_fields.append("published_build")+ else:+ build = version.builds.filter(status__in=CanvasBuild.ACTIVE_STATUSES).order_by("-created_at").first()+ if build is None:+ _lock_team_build_capacity(canvas.team_id)+ _assert_build_capacity(canvas.team_id)+ build = _queue_build(version)+ canvas.save(update_fields=update_fields)++ changes = _capabilities_changes(_version_capabilities(canvas.team_id, previous_head_id), version.capabilities)+ _log_canvas_activity(+ canvas,+ user=user,+ was_impersonated=was_impersonated,+ activity="published",+ detail=Detail(name=canvas.name, changes=changes),+ )+ return canvas, build+++def _version_capabilities(team_id: int, version_id: str | UUID | None) -> dict | None:+ """The declared capabilities of a source version, or None when there is no such+ version. None means "predates the capabilities snapshot", not an empty manifest."""+ if not version_id:+ return None+ return (+ CanvasSourceVersion.objects.for_team(team_id)+ .filter(pk=version_id)+ .values_list("capabilities", flat=True)+ .first()+ )+++def _capabilities_changes(before: dict | None, after: dict | None) -> list[Change] | None:+ """A one-field Change list recording a capabilities-manifest diff, or None when unchanged."""+ if before == after:+ return None+ return [Change(type="Canvas", action="changed", field="capabilities", before=before, after=after)]++def _log_canvas_activity(canvas: Canvas, *, user: User | None, was_impersonated: bool, activity: str, detail: Detail) -> None:diff --git a/products/canvas/backend/capabilities.py b/products/canvas/backend/capabilities.pynew file mode 100644index 000000000000..cf02b0501601--- /dev/null+++ b/products/canvas/backend/capabilities.py@@ -0,0 +1,58 @@+"""Comparison of canvas capability manifests.++A canvas's declared capabilities (`project.capabilities`) are its permission+boundary: which insights it may read, which events it may capture, whether it+may run inline queries, and which network origins it may reach. Widening that+boundary is the security-relevant direction, so it gets a first-class,+structured answer rather than a raw manifest diff.+"""++from dataclasses import dataclass+++def _posthog_section(manifest: dict | None) -> dict:+ return (manifest or {}).get("posthog") or {}+++def _network_origins(manifest: dict | None) -> list[str]:+ return ((manifest or {}).get("network") or {}).get("origins") or []+++@dataclass(frozen=True, kw_only=True)+class CapabilityWidening:+ """What `after` declares beyond `before`. Narrowings are not reported here+ because this type carries the pre-publish "this grants more access" signal;+ the activity log records the full diff for history."""++ insights_added: list[str]+ capture_events_added: list[str]+ inline_queries_enabled: bool+ network_origins_added: list[str]++ @property+ def widens(self) -> bool:+ return bool(+ self.insights_added+ or self.capture_events_added+ or self.inline_queries_enabled+ or self.network_origins_added+ )+++def capability_widening(before: dict | None, after: dict | None) -> CapabilityWidening:+ """How `after`'s declared capabilities grow `before`'s.++ A `before` of None (a baseline that predates the capabilities snapshot)+ is treated as empty, so everything `after` declares reports as an+ addition, because over-flagging is the safe direction for an advisory signal.+ """+ before_ph = _posthog_section(before)+ after_ph = _posthog_section(after)+ return CapabilityWidening(+ insights_added=sorted(set(after_ph.get("insights") or []) - set(before_ph.get("insights") or [])),+ capture_events_added=sorted(+ set(after_ph.get("captureEvents") or []) - set(before_ph.get("captureEvents") or [])+ ),+ inline_queries_enabled=bool(after_ph.get("inlineQueries")) and not bool(before_ph.get("inlineQueries")),+ network_origins_added=sorted(set(_network_origins(after)) - set(_network_origins(before))),+ )diff --git a/products/canvas/backend/migrations/0010_canvassourceversion_draft.py b/products/canvas/backend/migrations/0010_canvassourceversion_draft.pynew file mode 100644index 000000000000..0b1b4db4dbd7--- /dev/null+++ b/products/canvas/backend/migrations/0010_canvassourceversion_draft.py@@ -0,0 +1,17 @@+# Generated by Django 5.2.17 on 2026-08-10 10:36++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("canvas", "0009_canvassourceversion_capabilities"),+ ]++ operations = [+ migrations.AddField(+ model_name="canvassourceversion",+ name="draft",+ field=models.BooleanField(default=False),+ ),+ ]diff --git a/products/canvas/backend/migrations/max_migration.txt b/products/canvas/backend/migrations/max_migration.txtindex c8eb8fb45d76..8ef21ba2c32e 100644--- a/products/canvas/backend/migrations/max_migration.txt+++ b/products/canvas/backend/migrations/max_migration.txt@@ -1 +1 @@-0009_canvassourceversion_capabilities+0010_canvassourceversion_draftdiff --git a/products/canvas/backend/models.py b/products/canvas/backend/models.pyindex 61be0ac7a706..9969f7a244e2 100644--- a/products/canvas/backend/models.py+++ b/products/canvas/backend/models.py@@ -86,6 +86,11 @@ class CanvasSourceVersion(TeamScopedRootMixin, UUIDModel):# without reading object storage. Null for versions that predate it.capabilities = models.JSONField(null=True, blank=True)+ # True while the version is a staged draft: stored and built like any other+ # version, but never the canvas head, so its build can't go live. Promoting+ # clears the flag; after that the version is indistinguishable from a publish.+ draft = models.BooleanField(default=False)+created_by = models.ForeignKey("posthog.User", on_delete=models.SET_NULL, null=True, blank=True, db_constraint=False)diff --git a/products/canvas/backend/presentation/serializers.py b/products/canvas/backend/presentation/serializers.pyindex babd99b9c52f..bc6d849c311d 100644--- a/products/canvas/backend/presentation/serializers.py+++ b/products/canvas/backend/presentation/serializers.py@@ -221,10 +221,29 @@ class CanvasVersionSerializer(serializers.Serializer):)prompt = serializers.CharField(allow_null=True, help_text="Short description recorded with the publish.")task_id = serializers.UUIDField(allow_null=True, help_text="Task that published the version, when one did.")+ draft = serializers.BooleanField(+ help_text="True for a staged draft version that has never been the canvas head; promote it to make it live."+ )created_by = UserBasicSerializer(read_only=True, allow_null=True)created_at = serializers.DateTimeField(help_text="When the version was published.")+class CanvasDraftSerializer(serializers.Serializer):+ """A staged draft version and the status of its latest build. Preview a+ draft's files with `source?version_id=`, then make it live with `promote`."""++ version_id = serializers.CharField(help_text="Id of the draft source version.")+ prompt = serializers.CharField(allow_null=True, help_text="Short description recorded when the draft was staged.")+ created_by = UserBasicSerializer(read_only=True, allow_null=True, help_text="Who staged the draft.")+ created_at = serializers.DateTimeField(help_text="When the draft was staged.")+ build_status = serializers.ChoiceField(+ choices=["queued", "building", "ready", "failed"],+ allow_null=True,+ help_text="Status of the draft's latest build; null when no build has been recorded yet.",+ )+ build_id = serializers.CharField(allow_null=True, help_text="Id of the draft's latest build, when one exists.")++class CanvasSourceResponseSerializer(serializers.Serializer):"""A canvas's source project plus the version pointer edits must be based on."""@@ -475,3 +494,66 @@ class CanvasRevertSerializer(serializers.Serializer):expected_current_version_id = serializers.UUIDField(allow_null=True, help_text="Current source version observed before requesting the revert.")+++class CanvasSourceDraftSerializer(serializers.Serializer):+ """Payload for staging a complete source project as a draft build."""++ project = CanvasSourceProjectSerializer(help_text="The complete source project to stage as a draft.")+ prompt = serializers.CharField(+ required=False,+ allow_blank=True,+ trim_whitespace=False,+ help_text="Short description of the change, stored on the draft's version history entry.",+ )+++class CanvasCapabilityWideningSerializer(serializers.Serializer):+ """How a draft's declared capabilities grow the current head's. A head that+ predates the capabilities snapshot reports every declaration as an addition."""++ widens = serializers.BooleanField(+ help_text="True when the draft declares any capability the current head does not."+ )+ insights_added = serializers.ListField(+ child=serializers.CharField(),+ help_text="Insight short ids the draft newly declares access to.",+ )+ capture_events_added = serializers.ListField(+ child=serializers.CharField(),+ help_text="Event names the draft newly declares it may capture.",+ )+ inline_queries_enabled = serializers.BooleanField(+ help_text="True when the draft enables inline queries and the current head does not."+ )+ network_origins_added = serializers.ListField(+ child=serializers.CharField(),+ help_text="Network origins the draft newly declares it may reach.",+ )+++class CanvasSourceDraftResponseSerializer(serializers.Serializer):+ """Result of staging a draft build."""++ version_id = serializers.CharField(help_text="Id of the draft source version this request created.")+ build = CanvasBuildSerializer(help_text="The queued draft build; poll `builds` until it is terminal.")+ diagnostics = CanvasDiagnosticSerializer(+ many=True,+ help_text="Advisory (warning-severity) diagnostics recorded for the drafted project.",+ )+ capability_widening = CanvasCapabilityWideningSerializer(+ help_text="What the draft's declared capabilities grant beyond the current head's. Review before promoting."+ )+++class CanvasPromoteSerializer(serializers.Serializer):+ """Payload for promoting a draft version to the canvas's live head."""++ version_id = serializers.UUIDField(help_text="Id of the draft source version to make live.")+ expected_current_version_id = serializers.UUIDField(+ allow_null=True,+ help_text=(+ "Current source version observed before requesting the promote (null when the canvas has never "+ "been published). A moved head is rejected with 409 version_conflict."+ ),+ )diff --git a/products/canvas/backend/presentation/views.py b/products/canvas/backend/presentation/views.pyindex cdc74d2c7ccf..cd8fc57596d7 100644--- a/products/canvas/backend/presentation/views.py+++ b/products/canvas/backend/presentation/views.py@@ -28,10 +28,15 @@ from products.canvas.backend.presentation.serializers import (CanvasBuildActionSerializer,CanvasBuildSerializer,CanvasBuildsResponseSerializer,+ CanvasCapabilityWideningSerializer,CanvasCreateSerializer,+ CanvasDraftSerializer,+ CanvasPromoteSerializer,CanvasPublishConflictSerializer,CanvasRevertSerializer,CanvasSerializer,+ CanvasSourceDraftResponseSerializer,+ CanvasSourceDraftSerializer,CanvasSourceEditSerializer,CanvasSourceInvalidSerializer,CanvasSourcePublishResponseSerializer,@@ -96,13 +101,15 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):queryset = Canvas.objects.unscoped().select_related("created_by")serializer_class = CanvasSerializerhttp_method_names = ["get", "post", "patch", "delete", "head", "options"]- scope_object_read_actions = ["list", "retrieve", "source", "versions", "builds", "validate"]+ scope_object_read_actions = ["list", "retrieve", "source", "versions", "drafts", "builds", "validate"]scope_object_write_actions = ["create","partial_update","destroy","publish","edit",+ "draft",+ "promote","revert","build_action",]@@ -284,9 +291,18 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):)@action(methods=["GET"], detail=True)def versions(self, request: Request, *args: Any, **kwargs: Any) -> Response:- """The canvas's source-version history, newest first (metadata only)."""+ """The canvas's published source-version history, newest first (metadata only).++ Drafts are excluded: they are staged versions that have never been the+ head, so they are not part of the undo/revert timeline. Fetch a draft's+ files with `source?version_id=` to preview it before promoting.+ """canvas = self.get_object()- versions = canvas.source_versions.select_related("created_by").order_by("-created_at")[:VERSIONS_WINDOW]+ versions = (+ canvas.source_versions.filter(draft=False)+ .select_related("created_by")+ .order_by("-created_at")[:VERSIONS_WINDOW]+ )page = self.paginate_queryset(versions)if page is not None:return self.get_paginated_response(CanvasVersionSerializer(page, many=True).data)@@ -465,6 +481,155 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):})+ @extend_schema(+ operation_id="canvases_drafts_retrieve",+ responses={200: CanvasDraftSerializer(many=True)},+ request=None,+ )+ @action(methods=["GET"], detail=True)+ def drafts(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """The canvas's staged draft versions, newest first, each with its latest build status.++ A draft is a version that was built but never made the head. Preview one+ with `source?version_id=`, then make it live with `promote`.+ """+ canvas = self.get_object()+ draft_versions = list(+ canvas.source_versions.filter(draft=True)+ .select_related("created_by")+ .order_by("-created_at")[:VERSIONS_WINDOW]+ )+ # Newest build per draft version. Only the id/status/version are needed,+ # so skip the heavy manifest/diagnostics JSON columns.+ latest_build_by_version: dict[Any, CanvasBuild] = {}+ for build in (+ canvas.builds.filter(source_version_id__in=[version.id for version in draft_versions])+ .only("id", "source_version_id", "status")+ .order_by("source_version_id", "-created_at")+ ):+ latest_build_by_version.setdefault(build.source_version_id, build)+ data = []+ for version in draft_versions:+ build = latest_build_by_version.get(version.id)+ data.append(+ {+ "version_id": str(version.id),+ "prompt": version.prompt,+ "created_by": version.created_by,+ "created_at": version.created_at,+ "build_status": build.status if build else None,+ "build_id": str(build.id) if build else None,+ }+ )+ return Response(CanvasDraftSerializer(data, many=True).data)++ @extend_schema(+ operation_id="canvases_draft_create",+ request=CanvasSourceDraftSerializer,+ responses={+ 200: CanvasSourceDraftResponseSerializer,+ 400: OpenApiResponse(+ response=CanvasSourceInvalidSerializer,+ description="The source project failed validation.",+ ),+ 429: OpenApiResponse(description="The team's build capacity is exhausted; retry shortly."),+ },+ )+ @action(methods=["POST"], detail=True)+ def draft(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """Stage a complete source project as a draft version and build it, without publishing.++ The draft gets the same validation, versioning, and server-side build as+ a publish, but the canvas's head and live build never move, so nothing+ changes for viewers. Promote the version with `promote` to make it live.+ The response reports how the draft's declared capabilities widen the+ current head's, so growth in access can be reviewed before it ships.+ No version guard applies: a draft conflicts with nothing.+ """+ canvas = self.get_object()+ payload = CanvasSourceDraftSerializer(data=request.data)+ payload.is_valid(raise_exception=True)+ project = payload.validated_data["project"]+ diagnostics = validate_source_project(project)+ if has_errors(diagnostics):+ return _invalid_response(diagnostics)+ task_id = self._sandbox_task_id(request)+ try:+ version, build, widening = build_service.create_draft_version(+ canvas,+ project=project,+ prompt=payload.validated_data.get("prompt"),+ task_id=task_id,+ created_by=self._request_user(),+ was_impersonated=is_impersonated(request),+ )+ except build_service.CanvasBuildCapacityExceeded:+ return _capacity_response()+ except ObjectStorageError:+ return Response(+ {"detail": "Canvas source storage is temporarily unavailable; the draft was not saved."},+ status=status.HTTP_503_SERVICE_UNAVAILABLE,+ )+ self._report_canvas_action(+ "canvas draft created",+ canvas,+ version_id=str(version.id),+ widens_capabilities=widening.widens,+ is_sandbox_draft=task_id is not None,+ )+ return Response(+ {+ "version_id": str(version.id),+ "build": CanvasBuildSerializer(build).data,+ "diagnostics": diagnostics,+ "capability_widening": CanvasCapabilityWideningSerializer(widening).data,+ }+ )++ @extend_schema(+ operation_id="canvases_promote_create",+ request=CanvasPromoteSerializer,+ responses={+ 200: CanvasBuildSerializer,+ 409: OpenApiResponse(+ response=CanvasPublishConflictSerializer,+ description="The canvas moved past expected_current_version_id (a concurrent publish or a revert).",+ ),+ 429: OpenApiResponse(description="The team's build capacity is exhausted; retry shortly."),+ },+ )+ @action(methods=["POST"], detail=True)+ def promote(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """Make a draft version the canvas's live head.++ A draft whose build is ready goes live immediately, with no rebuild;+ otherwise a fresh build is queued. Returns that build.+ """+ canvas = self.get_object()+ payload = CanvasPromoteSerializer(data=request.data)+ payload.is_valid(raise_exception=True)+ try:+ canvas, build = build_service.promote_draft_version(+ canvas,+ payload.validated_data["version_id"],+ 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()+ except CanvasSourceVersion.DoesNotExist:+ return Response({"detail": "Draft version not found for this canvas."}, status=status.HTTP_404_NOT_FOUND)+ self._report_canvas_action(+ "canvas draft promoted",+ canvas,+ version_id=str(payload.validated_data["version_id"]),+ build_reused=build.status == CanvasBuild.STATUS_READY,+ )+ return Response(CanvasBuildSerializer(build).data)+@extend_schema(operation_id="canvases_revert_create",request=CanvasRevertSerializer,diff --git a/products/canvas/backend/tests/test_build_service.py b/products/canvas/backend/tests/test_build_service.pyindex c3deb67a175f..cc383bfdbc10 100644--- a/products/canvas/backend/tests/test_build_service.py+++ b/products/canvas/backend/tests/test_build_service.py@@ -87,6 +87,32 @@ class TestRunCanvasBuild(BuildServiceBaseTest):entry_key = f"{build.artifact_object_prefix}/index.html"assert self.storage.objects[entry_key] == b"<html></html>"+ def test_draft_build_ready_does_not_advance_pointer(self):+ published = self._publish()+ with patch.object(+ build_service, "run_cloud_builder", return_value=_builder_result({"index.html": "<html></html>"})+ ):+ build_service.run_canvas_build(self.team.id, str(published.id))+ self.canvas.refresh_from_db()++ _version, draft_build, _widening = build_service.create_draft_version(+ self.canvas,+ project=synthetic_source_project("export default function C() { return 2 }"),+ prompt=None,+ task_id=None,+ created_by=None,+ )+ with patch.object(+ build_service, "run_cloud_builder", return_value=_builder_result({"index.html": "<html>2</html>"})+ ):+ build_service.run_canvas_build(self.team.id, str(draft_build.id))++ draft_build.refresh_from_db()+ self.canvas.refresh_from_db()+ assert draft_build.status == CanvasBuild.STATUS_READY+ assert draft_build.artifact_object_prefix+ assert self.canvas.published_build_id == published.id+def test_stale_head_does_not_advance_pointer(self):build = self._publish()second = self._publish() # supersedes the first build, moves the headdiff --git a/products/canvas/backend/tests/test_canvas_api.py b/products/canvas/backend/tests/test_canvas_api.pyindex 7dac511ed4e3..a3725d9076bc 100644--- a/products/canvas/backend/tests/test_canvas_api.py+++ b/products/canvas/backend/tests/test_canvas_api.py@@ -4,6 +4,8 @@ from uuid import uuid4from posthog.test.base import APIBaseTestfrom unittest.mock import patch+from django.utils import timezone+from rest_framework import statusfrom posthog.models.activity_logging.activity_log import ActivityLog@@ -64,6 +66,15 @@ class CanvasAPIBaseTest(APIBaseTest):format="json",)+ def _activity(self, activity: str) -> list[ActivityLog]:+ return list(+ ActivityLog.objects.filter(team_id=self.team.id, scope="Canvas", activity=activity).order_by("created_at")+ )++ def _changes(self, entry: ActivityLog) -> list[dict[str, Any]]:+ assert entry.detail is not None+ return entry.detail["changes"]+class TestCanvasCrud(CanvasAPIBaseTest):def test_missing_user_only_sees_public_channels(self):@@ -487,15 +498,6 @@ class TestCanvasRevertAndBuilds(CanvasAPIBaseTest):class TestCanvasActivityLog(CanvasAPIBaseTest):- def _activity(self, activity: str) -> list[ActivityLog]:- return list(- ActivityLog.objects.filter(team_id=self.team.id, scope="Canvas", activity=activity).order_by("created_at")- )-- def _changes(self, entry: ActivityLog) -> list[dict[str, Any]]:- assert entry.detail is not None- return entry.detail["changes"]-def test_publish_snapshots_capabilities_and_logs_the_diff(self):canvas_id = self._create_canvas()first = self._publish(canvas_id, expected_current_version_id=None)@@ -598,3 +600,178 @@ class TestCanvasActivityVisibility(CanvasAPIBaseTest):self.organization.id, self.user)assert str(private.id) in activity_visibility.hidden_personal_canvas_ids_for_org(self.organization.id, other)+++class TestCanvasDraftBuilds(CanvasAPIBaseTest):+ def _draft(self, canvas_id: str, project: dict | None = None, **payload):+ return self.client.post(+ f"/api/projects/{self.team.id}/canvases/{canvas_id}/draft/",+ {"project": project or self._project(), **payload},+ format="json",+ )++ def _promote(self, canvas_id: str, version_id: str, expected: str | None):+ return self.client.post(+ f"/api/projects/{self.team.id}/canvases/{canvas_id}/promote/",+ {"version_id": version_id, "expected_current_version_id": expected},+ format="json",+ )++ def _published_canvas(self) -> tuple[str, str]:+ canvas_id = self._create_canvas()+ response = self._publish(canvas_id, expected_current_version_id=None)+ assert response.status_code == status.HTTP_200_OK, response.json()+ return canvas_id, response.json()["current_version_id"]++ def test_draft_stages_version_and_build_without_moving_head(self):+ canvas_id, head_id = self._published_canvas()++ response = self._draft(canvas_id, self._project("export default function C() { return 2 }"))+ assert response.status_code == status.HTTP_200_OK, response.json()+ body = response.json()+ assert body["version_id"] != head_id+ assert body["build"]["build_status"] == "queued"++ builds = self.client.get(f"/api/projects/{self.team.id}/canvases/{canvas_id}/builds/").json()+ assert builds["current_version_id"] == head_id++ # A draft stays out of the published-history timeline (undo/revert), so+ # only the head shows there and the draft is not revertable onto.+ version_ids = [+ row["id"]+ for row in self.client.get(f"/api/projects/{self.team.id}/canvases/{canvas_id}/versions/").json()["results"]+ ]+ assert version_ids == [head_id]++ def test_drafts_endpoint_lists_drafts_with_build_status(self):+ canvas_id, head_id = self._published_canvas()+ draft_body = self._draft(canvas_id, self._project("export default function C() { return 2 }")).json()++ drafts = self.client.get(f"/api/projects/{self.team.id}/canvases/{canvas_id}/drafts/").json()+ assert [row["version_id"] for row in drafts] == [draft_body["version_id"]]+ assert drafts[0]["build_status"] == "queued"+ assert drafts[0]["build_id"] == draft_body["build"]["id"]++ def test_draft_is_not_revertable(self):+ canvas_id, head_id = self._published_canvas()+ draft_version_id = self._draft(canvas_id).json()["version_id"]++ response = self.client.post(+ f"/api/projects/{self.team.id}/canvases/{canvas_id}/revert/",+ {"version_id": draft_version_id, "expected_current_version_id": head_id},+ format="json",+ )+ assert response.status_code == status.HTTP_404_NOT_FOUND++ def test_draft_reports_capability_widening_over_head(self):+ canvas_id, head_id = self._published_canvas()++ widened = self._project("export default function C() { return 2 }")+ widened["capabilities"] = {+ "posthog": {"insights": ["abc123"], "inlineQueries": True, "captureEvents": []},+ "network": {"origins": []},+ }+ response = self._draft(canvas_id, widened)+ widening = response.json()["capability_widening"]+ assert widening["widens"] is True+ assert widening["insights_added"] == ["abc123"]+ assert widening["inline_queries_enabled"] is True++ entries = self._activity("drafted")+ assert len(entries) == 1+ changes = self._changes(entries[0])+ assert changes[0]["field"] == "capabilities"++ unchanged = self._draft(canvas_id, self._project("export default function C() { return 3 }"))+ assert unchanged.json()["capability_widening"]["widens"] is False++ def test_promote_reuses_ready_build_and_moves_head(self):+ canvas_id, head_id = self._published_canvas()+ draft_body = self._draft(canvas_id, self._project("export default function C() { return 2 }")).json()+ draft_version_id = draft_body["version_id"]+ CanvasBuild.objects.for_team(self.team.id).filter(id=draft_body["build"]["id"]).update(+ status=CanvasBuild.STATUS_READY,+ artifact_object_prefix="canvas_artifact/test",+ finished_at=timezone.now(),+ )+ enqueued_before = self.enqueue.call_count++ response = self._promote(canvas_id, draft_version_id, expected=head_id)+ assert response.status_code == status.HTTP_200_OK, response.json()+ assert response.json()["id"] == draft_body["build"]["id"]+ assert response.json()["build_status"] == "ready"+ assert self.enqueue.call_count == enqueued_before++ builds = self.client.get(f"/api/projects/{self.team.id}/canvases/{canvas_id}/builds/").json()+ assert builds["current_version_id"] == draft_version_id+ assert builds["published_build_id"] == draft_body["build"]["id"]+ versions = {+ row["id"]: row+ for row in self.client.get(f"/api/projects/{self.team.id}/canvases/{canvas_id}/versions/").json()["results"]+ }+ assert versions[draft_version_id]["draft"] is False+ assert len(self._activity("published")) == 2++ def test_promote_rebuilds_when_artifacts_pruned(self):+ canvas_id, head_id = self._published_canvas()+ draft_body = self._draft(canvas_id).json()+ CanvasBuild.objects.for_team(self.team.id).filter(id=draft_body["build"]["id"]).update(+ status=CanvasBuild.STATUS_READY, artifact_object_prefix=None, finished_at=timezone.now()+ )++ response = self._promote(canvas_id, draft_body["version_id"], expected=head_id)+ assert response.status_code == status.HTTP_200_OK, response.json()+ assert response.json()["id"] != draft_body["build"]["id"]+ assert response.json()["build_status"] == "queued"++ def test_promote_adopts_in_flight_build_without_requeuing(self):+ # Promoting while the draft's build is still running must adopt that+ # build, not queue a duplicate of the same version — _finalize_ready+ # advances the live pointer once it completes, now that the version is+ # the head.+ canvas_id, head_id = self._published_canvas()+ draft_body = self._draft(canvas_id).json()+ CanvasBuild.objects.for_team(self.team.id).filter(id=draft_body["build"]["id"]).update(+ status=CanvasBuild.STATUS_BUILDING+ )+ published_before = self.client.get(f"/api/projects/{self.team.id}/canvases/{canvas_id}/builds/").json()[+ "published_build_id"+ ]+ enqueued_before = self.enqueue.call_count++ response = self._promote(canvas_id, draft_body["version_id"], expected=head_id)+ assert response.status_code == status.HTTP_200_OK, response.json()+ assert response.json()["id"] == draft_body["build"]["id"]+ assert response.json()["build_status"] == "building"+ assert self.enqueue.call_count == enqueued_before+ assert (+ CanvasBuild.objects.for_team(self.team.id).filter(source_version_id=draft_body["version_id"]).count() == 1+ )++ builds = self.client.get(f"/api/projects/{self.team.id}/canvases/{canvas_id}/builds/").json()+ assert builds["current_version_id"] == draft_body["version_id"]+ # The live artifact does not move until the adopted build finalizes.+ assert builds["published_build_id"] == published_before++ def test_draft_rejects_at_capacity_before_uploading(self):+ canvas_id, _ = self._published_canvas()+ objects_before = set(self.storage.objects)++ with patch.object(build_service, "MAX_ACTIVE_CANVAS_BUILDS_PER_TEAM", 0):+ response = self._draft(canvas_id, self._project("export default function C() { return 3 }"))++ assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS+ assert set(self.storage.objects) == objects_before++ def test_promote_rejects_stale_guard_and_non_draft_versions(self):+ canvas_id, head_id = self._published_canvas()+ draft_version_id = self._draft(canvas_id).json()["version_id"]++ stale = self._promote(canvas_id, draft_version_id, expected=str(uuid4()))+ assert stale.status_code == status.HTTP_409_CONFLICT++ not_a_draft = self._promote(canvas_id, head_id, expected=head_id)+ assert not_a_draft.status_code == status.HTTP_404_NOT_FOUND++ builds = self.client.get(f"/api/projects/{self.team.id}/canvases/{canvas_id}/builds/").json()+ assert builds["current_version_id"] == head_iddiff --git a/products/canvas/backend/tests/test_capabilities.py b/products/canvas/backend/tests/test_capabilities.pynew file mode 100644index 000000000000..5123a33284ec--- /dev/null+++ b/products/canvas/backend/tests/test_capabilities.py@@ -0,0 +1,43 @@+from unittest import TestCase++from parameterized import parameterized++from products.canvas.backend.capabilities import capability_widening++BASE = {+ "posthog": {"insights": ["abc"], "captureEvents": ["clicked"], "inlineQueries": False},+ "network": {"origins": []},+}+WIDER = {+ "posthog": {"insights": ["abc", "def"], "captureEvents": ["clicked"], "inlineQueries": True},+ "network": {"origins": ["https://api.example.com"]},+}+NARROWER = {+ "posthog": {"insights": [], "captureEvents": [], "inlineQueries": False},+ "network": {"origins": []},+}+++class TestCapabilityWidening(TestCase):+ @parameterized.expand(+ [+ ("identical", BASE, BASE, False),+ ("narrowing_only", BASE, NARROWER, False),+ ("unknown_baseline_flags_everything", None, BASE, True),+ ("empty_manifests", {}, {}, False),+ ]+ )+ def test_widens_flag(self, _name, before, after, expected):+ assert capability_widening(before, after).widens is expected++ def test_reports_each_added_capability(self):+ widening = capability_widening(BASE, WIDER)+ assert widening.widens is True+ assert widening.insights_added == ["def"]+ assert widening.capture_events_added == []+ assert widening.inline_queries_enabled is True+ assert widening.network_origins_added == ["https://api.example.com"]++ def test_inline_queries_already_enabled_is_not_a_widening(self):+ enabled = {"posthog": {"inlineQueries": True}}+ assert capability_widening(enabled, enabled).widens is Falsediff --git a/products/canvas/frontend/activityDescriber.test.tsx b/products/canvas/frontend/activityDescriber.test.tsxindex c47dd07f8308..bfe4e2ad0333 100644--- a/products/canvas/frontend/activityDescriber.test.tsx+++ b/products/canvas/frontend/activityDescriber.test.tsx@@ -96,6 +96,30 @@ describe('canvasActivityDescriber', () => {expect(text).not.toContain('capabilities')})+ it('summarizes a draft and the capabilities it would add', () => {+ const text = getTextContent(+ canvasActivityDescriber(+ canvasLogItem({+ activity: 'drafted',+ detail: {+ merge: null,+ trigger: null,+ name: 'Signups board',+ changes: [+ capabilitiesChange(+ { posthog: { insights: [], inlineQueries: false, captureEvents: [] } },+ { posthog: { insights: ['abc123'], inlineQueries: false, captureEvents: [] } }+ ),+ ],+ },+ })+ )+ )+ expect(text).toContain('drafted a new version of canvas Signups board')+ expect(text).toContain('declared insight abc123')+ expect(text).not.toContain('published')+ })+it.each([['name',diff --git a/products/canvas/frontend/activityDescriber.tsx b/products/canvas/frontend/activityDescriber.tsxindex 613d26cf6ad7..cc91637adce6 100644--- a/products/canvas/frontend/activityDescriber.tsx+++ b/products/canvas/frontend/activityDescriber.tsx@@ -117,6 +117,21 @@ export function canvasActivityDescriber(logItem: ActivityLogItem, asNotification}}+ if (logItem.activity === 'drafted') {+ const capabilitiesChange = (logItem.detail.changes || []).find((change) => change.field === 'capabilities')+ const parts = capabilitiesChange ? describeCapabilitiesChange(capabilitiesChange) : []+ return {+ description: (+ <>+ {actor} drafted a new version of canvas {canvasName}+ {parts.length === 1 ? <> that</> : null}+ {parts.length > 1 ? <> that changes its declared capabilities:</> : null}+ {parts.length > 0 ? inlineOrList(parts) : null}+ </>+ ),+ }+ }+if (logItem.activity === 'reverted') {return {description: (diff --git a/products/canvas/frontend/generated/api.schemas.ts b/products/canvas/frontend/generated/api.schemas.tsindex fc18800506ad..a2e7b2804b58 100644--- a/products/canvas/frontend/generated/api.schemas.ts+++ b/products/canvas/frontend/generated/api.schemas.ts@@ -313,102 +313,6 @@ export interface CanvasBuildActionApi {build_id: string}-/**- * One per-file edit: set a file's content, or delete it.- */-export interface CanvasSourceEditOperationApi {- /** Project-relative path of the file to write or delete (e.g. "src/canvas.tsx"). */- path: string- /**- * The file's complete new content. Null (or omitted) deletes the file.- * @nullable- */- content?: string | null-}--/**- * Payload for publishing per-file edits against the canvas's current source.- */-export interface CanvasSourceEditApi {- /** Edits applied in order to the canvas's current source project. */- operations: CanvasSourceEditOperationApi[]- /** Short description of the change, stored on the appended version history entry. */- prompt?: string- /**- * Optional new display name for the canvas.- * @maxLength 400- */- name?: string- /**- * Required optimistic-concurrency guard: the current_version_id the edits are based on (null when the canvas has never been published). Diff edits against a moved head are rejected with 409 version_conflict — they cannot be published unguarded.- * @nullable- */- expected_current_version_id: string | null-}--/**- * Identity and version pointers for one canvas.- */-export interface CanvasSummaryApi {- /** The canvas's id. */- id: string- /** Display name of the canvas. */- name: string- /** Id of the channel the canvas belongs to. */- channel_id: string- /**- * Id of the live source version — pass as expected_current_version_id on publish. Null before the first publish.- * @nullable- */- current_version_id: string | null- /**- * Id of the canvas's live (last successful, still-eligible) build. Null until a build completes.- * @nullable- */- published_build_id: string | null- /** When the canvas was created. */- created_at: string-}--/**- * Result of a successful source-project publish.- */-export interface CanvasSourcePublishResponseApi {- /** The canvas after the publish, including the new version pointer. */- canvas: CanvasSummaryApi- /** Id of the source version this publish created. */- current_version_id: string- /** Advisory (warning-severity) diagnostics recorded for the published project. */- diagnostics: CanvasDiagnosticApi[]-}--/**- * 400 body for a publish whose source project failed validation.- */-export interface CanvasSourceInvalidApi {- /** Human-readable summary of why the project was rejected. */- detail: string- /** Always "invalid_source_project". */- code: string- /** The validation diagnostics, including at least one error. */- diagnostics: CanvasDiagnosticApi[]-}--/**- * 409 body for a guarded canvas publish based on a stale version.- */-export interface CanvasPublishConflictApi {- /** Human-readable description of the conflict and how to recover. */- detail: string- /** Always "version_conflict". */- code: string- /**- * The canvas's live current_version_id at rejection time (null when the canvas has no versions).- * @nullable- */- current_version_id: string | null-}-/*** * `base64` - base64*/@@ -515,6 +419,195 @@ export interface CanvasSourceProjectApi {capabilities?: CanvasCapabilitiesApi}+/**+ * Payload for staging a complete source project as a draft build.+ */+export interface CanvasSourceDraftApi {+ /** The complete source project to stage as a draft. */+ project: CanvasSourceProjectApi+ /** Short description of the change, stored on the draft's version history entry. */+ prompt?: string+}++/**+ * How a draft's declared capabilities grow the current head's. A head that+ * predates the capabilities snapshot reports every declaration as an addition.+ */+export interface CanvasCapabilityWideningApi {+ /** True when the draft declares any capability the current head does not. */+ widens: boolean+ /** Insight short ids the draft newly declares access to. */+ insights_added: string[]+ /** Event names the draft newly declares it may capture. */+ capture_events_added: string[]+ /** True when the draft enables inline queries and the current head does not. */+ inline_queries_enabled: boolean+ /** Network origins the draft newly declares it may reach. */+ network_origins_added: string[]+}++/**+ * Result of staging a draft build.+ */+export interface CanvasSourceDraftResponseApi {+ /** Id of the draft source version this request created. */+ version_id: string+ /** The queued draft build; poll `builds` until it is terminal. */+ build: CanvasBuildApi+ /** Advisory (warning-severity) diagnostics recorded for the drafted project. */+ diagnostics: CanvasDiagnosticApi[]+ /** What the draft's declared capabilities grant beyond the current head's. Review before promoting. */+ capability_widening: CanvasCapabilityWideningApi+}++/**+ * 400 body for a publish whose source project failed validation.+ */+export interface CanvasSourceInvalidApi {+ /** Human-readable summary of why the project was rejected. */+ detail: string+ /** Always "invalid_source_project". */+ code: string+ /** The validation diagnostics, including at least one error. */+ diagnostics: CanvasDiagnosticApi[]+}++/**+ * A staged draft version and the status of its latest build. Preview a+ * draft's files with `source?version_id=`, then make it live with `promote`.+ */+export interface CanvasDraftApi {+ /** Id of the draft source version. */+ version_id: string+ /**+ * Short description recorded when the draft was staged.+ * @nullable+ */+ prompt: string | null+ /** Who staged the draft. */+ readonly created_by: UserBasicApi | null+ /** When the draft was staged. */+ created_at: string+ /** Status of the draft's latest build; null when no build has been recorded yet.+ *+ * * `queued` - queued+ * * `building` - building+ * * `ready` - ready+ * * `failed` - failed */+ build_status: BuildStatusEnumApi | null+ /**+ * Id of the draft's latest build, when one exists.+ * @nullable+ */+ build_id: string | null+}++export interface PaginatedCanvasDraftListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: CanvasDraftApi[]+}++/**+ * One per-file edit: set a file's content, or delete it.+ */+export interface CanvasSourceEditOperationApi {+ /** Project-relative path of the file to write or delete (e.g. "src/canvas.tsx"). */+ path: string+ /**+ * The file's complete new content. Null (or omitted) deletes the file.+ * @nullable+ */+ content?: string | null+}++/**+ * Payload for publishing per-file edits against the canvas's current source.+ */+export interface CanvasSourceEditApi {+ /** Edits applied in order to the canvas's current source project. */+ operations: CanvasSourceEditOperationApi[]+ /** Short description of the change, stored on the appended version history entry. */+ prompt?: string+ /**+ * Optional new display name for the canvas.+ * @maxLength 400+ */+ name?: string+ /**+ * Required optimistic-concurrency guard: the current_version_id the edits are based on (null when the canvas has never been published). Diff edits against a moved head are rejected with 409 version_conflict — they cannot be published unguarded.+ * @nullable+ */+ expected_current_version_id: string | null+}++/**+ * Identity and version pointers for one canvas.+ */+export interface CanvasSummaryApi {+ /** The canvas's id. */+ id: string+ /** Display name of the canvas. */+ name: string+ /** Id of the channel the canvas belongs to. */+ channel_id: string+ /**+ * Id of the live source version — pass as expected_current_version_id on publish. Null before the first publish.+ * @nullable+ */+ current_version_id: string | null+ /**+ * Id of the canvas's live (last successful, still-eligible) build. Null until a build completes.+ * @nullable+ */+ published_build_id: string | null+ /** When the canvas was created. */+ created_at: string+}++/**+ * Result of a successful source-project publish.+ */+export interface CanvasSourcePublishResponseApi {+ /** The canvas after the publish, including the new version pointer. */+ canvas: CanvasSummaryApi+ /** Id of the source version this publish created. */+ current_version_id: string+ /** Advisory (warning-severity) diagnostics recorded for the published project. */+ diagnostics: CanvasDiagnosticApi[]+}++/**+ * 409 body for a guarded canvas publish based on a stale version.+ */+export interface CanvasPublishConflictApi {+ /** Human-readable description of the conflict and how to recover. */+ detail: string+ /** Always "version_conflict". */+ code: string+ /**+ * The canvas's live current_version_id at rejection time (null when the canvas has no versions).+ * @nullable+ */+ current_version_id: string | null+}++/**+ * Payload for promoting a draft version to the canvas's live head.+ */+export interface CanvasPromoteApi {+ /** Id of the draft source version to make live. */+ version_id: string+ /**+ * Current source version observed before requesting the promote (null when the canvas has never been published). A moved head is rejected with 409 version_conflict.+ * @nullable+ */+ expected_current_version_id: string | null+}+/*** Payload for publishing a complete canvas source project.*/@@ -603,6 +696,8 @@ export interface CanvasVersionApi {* @nullable*/task_id: string | null+ /** True for a staged draft version that has never been the canvas head; promote it to make it live. */+ draft: booleanreadonly created_by: UserBasicApi | null/** When the version was published. */created_at: string@@ -639,6 +734,17 @@ export type CanvasesBuildsRetrieveParams = {version_id?: string}+export type CanvasesDraftsRetrieveParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+}+export type CanvasesSourceRetrieveParams = {/*** Read this historical source version instead of the head (for version browsing).diff --git a/products/canvas/frontend/generated/api.ts b/products/canvas/frontend/generated/api.tsindex 5ce456ab7c30..53b27403ae81 100644--- a/products/canvas/frontend/generated/api.ts+++ b/products/canvas/frontend/generated/api.ts@@ -14,7 +14,10 @@ import type {CanvasBuildApi,CanvasBuildsResponseApi,CanvasCreateApi,+ CanvasPromoteApi,CanvasRevertApi,+ CanvasSourceDraftApi,+ CanvasSourceDraftResponseApi,CanvasSourceEditApi,CanvasSourcePublishApi,CanvasSourcePublishResponseApi,@@ -22,9 +25,11 @@ import type {CanvasValidateRequestApi,CanvasValidateResponseApi,CanvasesBuildsRetrieveParams,+ CanvasesDraftsRetrieveParams,CanvasesListParams,CanvasesSourceRetrieveParams,CanvasesVersionsRetrieveParams,+ PaginatedCanvasDraftListApi,PaginatedCanvasListApi,PaginatedCanvasVersionListApi,PatchedCanvasUpdateApi,@@ -194,6 +199,68 @@ export const canvasesBuildActionCreate = async (})}+export const getCanvasesDraftCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/canvases/${id}/draft/`+}++/**+ * Stage a complete source project as a draft version and build it, without publishing.+ *+ * The draft gets the same validation, versioning, and server-side build as+ * a publish, but the canvas's head and live build never move, so nothing+ * changes for viewers. Promote the version with `promote` to make it live.+ * The response reports how the draft's declared capabilities widen the+ * current head's, so growth in access can be reviewed before it ships.+ * No version guard applies: a draft conflicts with nothing.+ */+export const canvasesDraftCreate = async (+ projectId: string,+ id: string,+ canvasSourceDraftApi: CanvasSourceDraftApi,+ options?: RequestInit+): Promise<CanvasSourceDraftResponseApi> => {+ return apiMutator<CanvasSourceDraftResponseApi>(getCanvasesDraftCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(canvasSourceDraftApi),+ })+}++export const getCanvasesDraftsRetrieveUrl = (projectId: string, id: string, params?: CanvasesDraftsRetrieveParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/canvases/${id}/drafts/?${stringifiedParams}`+ : `/api/projects/${projectId}/canvases/${id}/drafts/`+}++/**+ * The canvas's staged draft versions, newest first, each with its latest build status.+ *+ * A draft is a version that was built but never made the head. Preview one+ * with `source?version_id=`, then make it live with `promote`.+ */+export const canvasesDraftsRetrieve = async (+ projectId: string,+ id: string,+ params?: CanvasesDraftsRetrieveParams,+ options?: RequestInit+): Promise<PaginatedCanvasDraftListApi> => {+ return apiMutator<PaginatedCanvasDraftListApi>(getCanvasesDraftsRetrieveUrl(projectId, id, params), {+ ...options,+ method: 'GET',+ })+}+export const getCanvasesEditCreateUrl = (projectId: string, id: string) => {return `/api/projects/${projectId}/canvases/${id}/edit/`}@@ -221,6 +288,30 @@ export const canvasesEditCreate = async (})}+export const getCanvasesPromoteCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/canvases/${id}/promote/`+}++/**+ * Make a draft version the canvas's live head.+ *+ * A draft whose build is ready goes live immediately, with no rebuild;+ * otherwise a fresh build is queued. Returns that build.+ */+export const canvasesPromoteCreate = async (+ projectId: string,+ id: string,+ canvasPromoteApi: CanvasPromoteApi,+ options?: RequestInit+): Promise<CanvasBuildApi> => {+ return apiMutator<CanvasBuildApi>(getCanvasesPromoteCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(canvasPromoteApi),+ })+}+export const getCanvasesPublishCreateUrl = (projectId: string, id: string) => {return `/api/projects/${projectId}/canvases/${id}/publish/`}@@ -345,7 +436,11 @@ export const getCanvasesVersionsRetrieveUrl = (}/**- * The canvas's source-version history, newest first (metadata only).+ * The canvas's published source-version history, newest first (metadata only).+ *+ * Drafts are excluded: they are staged versions that have never been the+ * head, so they are not part of the undo/revert timeline. Fetch a draft's+ * files with `source?version_id=` to preview it before promoting.*/export const canvasesVersionsRetrieve = async (projectId: string,diff --git a/products/canvas/frontend/generated/api.zod.ts b/products/canvas/frontend/generated/api.zod.tsindex 84718bed20d5..1888ba7fc10a 100644--- a/products/canvas/frontend/generated/api.zod.ts+++ b/products/canvas/frontend/generated/api.zod.ts@@ -56,6 +56,123 @@ export const CanvasesBuildActionCreateBody = /* @__PURE__ */ zod.object({build_id: zod.uuid(),})+/**+ * Stage a complete source project as a draft version and build it, without publishing.+ *+ * The draft gets the same validation, versioning, and server-side build as+ * a publish, but the canvas's head and live build never move, so nothing+ * changes for viewers. Promote the version with `promote` to make it live.+ * The response reports how the draft's declared capabilities widen the+ * current head's, so growth in access can be reviewed before it ships.+ * No version guard applies: a draft conflicts with nothing.+ */+export const canvasesDraftCreateBodyProjectOneAssetsContentMax = 2796204++export const canvasesDraftCreateBodyProjectOneAssetsContentRegExp = new RegExp(+ '^(?:[A-Za-z0-9+\/]{4})\*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$'+)+export const canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogInsightsItemMax = 128++export const canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogInsightsMax = 100++export const canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogCaptureEventsItemMax = 200++export const canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogCaptureEventsMax = 100++export const canvasesDraftCreateBodyProjectOneCapabilitiesOneNetworkOriginsItemMax = 2048++export const canvasesDraftCreateBodyProjectOneCapabilitiesOneNetworkOriginsMax = 20++export const CanvasesDraftCreateBody = /* @__PURE__ */ zod+ .object({+ project: zod+ .object({+ schemaVersion: zod.number().describe('Source-project schema version. Currently always 1.'),+ files: zod+ .record(zod.string(), zod.string())+ .describe("Project files keyed by relative path (forward slashes, no '..')."),+ assets: zod+ .record(+ zod.string(),+ zod.object({+ encoding: zod.enum(['base64']).describe('\* `base64` - base64'),+ contentType: zod+ .enum([+ 'image/png',+ 'image/jpeg',+ 'image/gif',+ 'image/webp',+ 'image/svg+xml',+ 'font/woff',+ 'font/woff2',+ 'application/wasm',+ 'application/octet-stream',+ ])+ .describe(+ '\* `image\/png` - image\/png\n\* `image\/jpeg` - image\/jpeg\n\* `image\/gif` - image\/gif\n\* `image\/webp` - image\/webp\n\* `image\/svg+xml` - image\/svg+xml\n\* `font\/woff` - font\/woff\n\* `font\/woff2` - font\/woff2\n\* `application\/wasm` - application\/wasm\n\* `application\/octet-stream` - application\/octet-stream'+ ),+ content: zod+ .string()+ .max(canvasesDraftCreateBodyProjectOneAssetsContentMax)+ .regex(canvasesDraftCreateBodyProjectOneAssetsContentRegExp),+ })+ )+ .optional()+ .describe('Optional base64-encoded binary assets keyed by safe project-relative paths.'),+ entryHtml: zod.string().describe('The project\'s entry HTML file. Currently always \"index.html\".'),+ dependencies: zod+ .record(zod.string(), zod.string())+ .optional()+ .describe(+ 'Exact-version dependencies, restricted to the platform-supported set (react, react-dom, @posthog\/quill, recharts, lucide-react, dayjs) at their pinned versions.'+ ),+ canvasSdkVersion: zod+ .string()+ .optional()+ .describe('Version of the host-injected `ph` canvas SDK the project targets.'),+ capabilities: zod+ .object({+ posthog: zod.object({+ insights: zod+ .array(+ zod+ .string()+ .max(canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogInsightsItemMax)+ )+ .max(canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogInsightsMax),+ inlineQueries: zod.boolean(),+ captureEvents: zod+ .array(+ zod+ .string()+ .max(+ canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogCaptureEventsItemMax+ )+ )+ .max(canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogCaptureEventsMax),+ }),+ network: zod.object({+ origins: zod+ .array(+ zod.url().max(canvasesDraftCreateBodyProjectOneCapabilitiesOneNetworkOriginsItemMax)+ )+ .max(canvasesDraftCreateBodyProjectOneCapabilitiesOneNetworkOriginsMax),+ }),+ })+ .optional()+ .describe(+ 'Bounded capabilities frozen into the built artifact. Declare every insight short id the canvas loads, every event it captures, and inlineQueries when it runs ad-hoc HogQL — the host enforces these at runtime and validation rejects undeclared `ph` calls.'+ ),+ })+ .describe("A canvas's multi-file source project — the canonical write format for canvas source.")+ .describe('The complete source project to stage as a draft.'),+ prompt: zod+ .string()+ .optional()+ .describe("Short description of the change, stored on the draft's version history entry."),+ })+ .describe('Payload for staging a complete source project as a draft build.')+/*** Publish per-file edits against the canvas's current source project.*@@ -104,6 +221,24 @@ export const CanvasesEditCreateBody = /* @__PURE__ */ zod}).describe("Payload for publishing per-file edits against the canvas's current source.")+/**+ * Make a draft version the canvas's live head.+ *+ * A draft whose build is ready goes live immediately, with no rebuild;+ * otherwise a fresh build is queued. Returns that build.+ */+export const CanvasesPromoteCreateBody = /* @__PURE__ */ zod+ .object({+ version_id: zod.uuid().describe('Id of the draft source version to make live.'),+ expected_current_version_id: zod+ .uuid()+ .nullable()+ .describe(+ 'Current source version observed before requesting the promote (null when the canvas has never been published). A moved head is rejected with 409 version_conflict.'+ ),+ })+ .describe("Payload for promoting a draft version to the canvas's live head.")+/*** Publish a complete source project as the canvas's new head version.*diff --git a/products/canvas/mcp/tools.yaml b/products/canvas/mcp/tools.yamlindex dc751bf030b9..d6e0a370a6af 100644--- a/products/canvas/mcp/tools.yaml+++ b/products/canvas/mcp/tools.yaml@@ -44,7 +44,52 @@ tools:intended target — list them with canvas-list first.param_overrides:channel_id:- description: Id of the channel to create the canvas in (resolve it with channel-list).+ description:+ "Id of the channel to create the canvas in — the channel the task was created in, from the task's context.+ Use channel-list only to resolve a channel the user named; never pick a channel from the listing+ yourself (the personal #me channel is not a default)."+ canvas-draft-create:+ operation: canvases_draft_create+ enabled: true+ scopes:+ - canvas:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: false+ title: Stage a canvas draft build+ description: >+ Build the COMPLETE source project of a canvas as a DRAFT, without changing the live canvas. The project is+ validated and built server-side exactly like a publish, but the canvas head and live build do NOT move, so+ viewers keep seeing the current version. For a canvas that already has a live version this is the DEFAULT+ way to save a change — the user previews and promotes it; use canvas-publish-create only for a first version+ or when the user explicitly asked to make the change live. Returns the draft's `version_id`, its queued+ build, and `capability_widening` — how the draft's declared capabilities grow the live version's (insights,+ capture events, inline queries, network origins) — so added access is visible before shipping. Poll+ canvas-builds-retrieve until the draft's build is terminal, preview the draft with canvas-source-retrieve+ passing the returned `version_id`, then make it live with canvas-promote-create. Declare runtime+ capabilities in `project.capabilities`.+ param_overrides:+ id:+ description: ID of the canvas to stage a draft for.+ canvas-drafts-retrieve:+ operation: canvases_drafts_retrieve+ enabled: true+ scopes:+ - canvas:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: List canvas drafts+ description: >+ List a canvas's staged drafts (from canvas-draft-create), newest first, each with its latest build status+ (queued/building/ready/failed). Drafts are separate from the published version history and are never the+ live version until promoted. Use this to find a pending draft to preview (canvas-source-retrieve with its+ `version_id`) and promote (canvas-promote-create).+ param_overrides:+ id:+ description: ID of the canvas whose drafts to list.canvas-edit-create:operation: canvases_edit_createenabled: true@@ -60,7 +105,9 @@ tools:operation sets a file's complete content, or deletes it when `content` is null.`expected_current_version_id` is REQUIRED (from canvas-source-retrieve; null only for a never-publishedcanvas) — a stale base is rejected with 409 version_conflict; re-read the source, re-apply, and edit again.- The edited project is validated first; error diagnostics reject the whole edit atomically.+ The edited project is validated first; error diagnostics reject the whole edit atomically. Edits go live+ like a publish — for a canvas with a live version, default to staging the complete project as a draft with+ canvas-draft-create instead, unless the user asked for an immediate live change.param_overrides:id:description: ID of the canvas whose source to edit.@@ -80,6 +127,26 @@ tools:param_overrides:channel:description: Only return canvases in this channel (channel id).+ canvas-promote-create:+ operation: canvases_promote_create+ enabled: true+ scopes:+ - canvas:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: false+ title: Promote a canvas draft to live+ description: >+ Make a draft version (staged with canvas-draft-create) the canvas's live head. A draft whose build is+ already ready goes live immediately with no rebuild; otherwise a fresh build is queued. Pass+ `expected_current_version_id` — the live `current_version_id` from canvas-source-retrieve — so a concurrent+ change is rejected with 409 version_conflict instead of overwritten. A 429 means the team's build capacity+ is exhausted; wait and retry. Returns the now-live build. This is the only way a draft reaches the head:+ revert does not act on drafts.+ param_overrides:+ id:+ description: ID of the canvas whose draft to promote.canvas-publish-create:operation: canvases_publish_createenabled: true@@ -91,7 +158,9 @@ tools:idempotent: falsetitle: Publish canvas source projectdescription: >- Publish the COMPLETE source project of a canvas as its new head version and queue a server-side build. The+ Publish the COMPLETE source project of a canvas as its new head version and queue a server-side build.+ Publishing goes live immediately: use it for a canvas's first version, or when the user explicitly asked to+ make a change live — otherwise stage the change with canvas-draft-create for the user to promote. Theproject is validated first — error diagnostics reject the publish (400) and leave the canvas untouched. Pass`expected_current_version_id` (from canvas-source-retrieve) so a concurrent edit is rejected with 409version_conflict instead of overwritten; on conflict, re-read the source, re-apply your edits, and publishdiff --git a/products/canvas/skills/building-canvases/SKILL.md b/products/canvas/skills/building-canvases/SKILL.mdindex 09bc962a9e35..8a16387540f0 100644--- a/products/canvas/skills/building-canvases/SKILL.md+++ b/products/canvas/skills/building-canvases/SKILL.md@@ -19,13 +19,17 @@ saves it.## Resolve the target canvas- If the task names a canvas id (canvas-initiated tasks do), that is the target. Do not create another.-- Otherwise — channel-composer tasks give the channel, not a canvas — list the channel's canvases- with `canvas-list` (scope with `channel`; resolve a bare channel name with `channel-list` first).- If one is clearly what the request refers to — an earlier iteration of the same board or tool —- build on it instead of creating a near-duplicate, and say so in your reply so the user knows- where the result landed.-- Only when nothing existing fits, create one with `canvas-create` in the right channel, named+- Otherwise the target channel is the one the task was created in — named in the task's context+ (the `channel_context` block or the generation instructions). List that channel's canvases with+ `canvas-list` (scope with `channel`). If one is clearly what the request refers to — an earlier+ iteration of the same board or tool — build on it instead of creating a near-duplicate, and say+ so in your reply so the user knows where the result landed.+- Only when nothing existing fits, create one with `canvas-create` in that same channel, namedwith a short descriptive title drawn from the request — never "Untitled canvas".+- Never survey channels to choose a target yourself: use `channel-list` only to resolve a channel+ the USER named to its id. Its listing puts the personal #me channel first, and #me is never a+ default — a canvas filed there is invisible to everyone else. If the task names neither a canvas+ nor a channel, ask which channel to use instead of guessing.## Choose the least complex implementation that meets the request@@ -50,14 +54,21 @@ user-visible requirement you cannot infer.ad-hoc queries) — the host enforces these at runtime and validation rejects undeclared calls.3. Validate with `canvas-validate-create` as often as needed and fix every error-severitydiagnostic.-4. Publish the complete project with `canvas-publish-create`, passing `expected_current_version_id`.- Follow the `validating-and-publishing-canvases` skill for diagnostics and conflict recovery.-5. **Wait for the build.** A publish queues a server-side build; poll `canvas-builds-retrieve`+4. Save the project — which tool depends on whether the canvas is already live:+ - **First version** (`current_version_id` is null): publish the complete project with+ `canvas-publish-create`, passing `expected_current_version_id: null`.+ - **Already live** (`current_version_id` is set): stage the complete project as a draft with+ `canvas-draft-create` — the user previews the draft and promotes it to live. Publish or+ promote yourself only when the user explicitly asked to make the change live.+ Follow the `validating-and-publishing-canvases` skill for diagnostics and conflict recovery.+5. **Wait for the build** — drafts and publishes alike queue one. Poll `canvas-builds-retrieve`(every few seconds, up to ~2 minutes) until your build is `ready` or `failed`. On `failed`,- read the build's error diagnostics, fix the project, and publish again — do not finish the+ read the build's error diagnostics, fix the project, and save again — do not finish thetask with a failed build.-Publish once per requested change, when the canvas is ready — not after every micro-edit.+Save once per requested change, when the canvas is ready — not after every micro-edit. When you+staged 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.## Source-project shapediff --git a/products/canvas/skills/validating-and-publishing-canvases/SKILL.md b/products/canvas/skills/validating-and-publishing-canvases/SKILL.mdindex e0a56bc187c9..79e7b2e9ff82 100644--- a/products/canvas/skills/validating-and-publishing-canvases/SKILL.md+++ b/products/canvas/skills/validating-and-publishing-canvases/SKILL.md@@ -3,10 +3,11 @@ name: validating-and-publishing-canvasesdescription: >Validate and publish a canvas source project safely: the source-project shape, declaredcapabilities, reading the current version pointer, iterating on validation diagnostics, guarded- publishing with expected_current_version_id, waiting out the queued build, and recovering from a- 409 version_conflict or a 429 capacity limit without overwriting concurrent work. Use whenever a- canvas edit is ready to save, a canvas publish or build returns diagnostics or a conflict, or a- task needs to understand canvas version history.+ publishing with expected_current_version_id, staging a draft build and promoting it, waiting out+ the queued build, and recovering from a 409 version_conflict or a 429 capacity limit without+ overwriting concurrent work. Use whenever a canvas edit is ready to save, a draft build is wanted,+ a canvas publish or build returns diagnostics or a conflict, or a task needs to understand canvas+ version history.---# Validating and publishing canvases@@ -58,7 +59,11 @@ Diagnostics carry `severity`, a stable `code`, a `message`, and (for file-specif## Publish guarded-Two ways to save, both guarded:+Publishing goes live immediately, so it is for a canvas's **first version** or for a change the+user explicitly asked to make live. A canvas that already has a live version defaults to a draft+instead — see "Draft, then promote" below.++Two ways to publish, both guarded:- **Whole project** — `canvas-publish-create` with the complete `project`.- **Per-file edits** — `canvas-edit-create` with `operations` (each sets a@@ -92,6 +97,37 @@ every few seconds (up to ~2 minutes) until the build you queued is terminal:build never replaces the last good one, so the canvas keeps rendering the previous version —finishing the task here would leave the user with a stale canvas and a silent failure.+## Draft, then promote++Publishing goes live the moment its build is ready. For a canvas that **already has a live+version**, that is not the default: stage the change as a draft and let the user promote it.+Publish directly only for a canvas's first version (nothing is live to protect) or when the user+explicitly asked to make the change live. A draft is a real, buildable version that is never the+head: the live canvas keeps rendering the current version until someone promotes the draft. This+is different from `canvas-validate-create`, which only compile-checks and produces no build or+preview.++1. **Stage** — `canvas-draft-create` with the complete `project` (same shape, capabilities, and+ validation as a publish). No `expected_current_version_id`: a draft is based on nothing and+ conflicts with nothing. The response returns the draft's `version_id`, its queued `build`, and+ `capability_widening` — the insights, capture events, inline queries, and network origins the+ draft declares beyond the live version. Surface a non-empty widening to the user before+ promoting; it is the access the change would newly grant.+2. **Wait for the build** — poll `canvas-builds-retrieve` until the draft's build is terminal, the+ same way you would after a publish. A failed draft build is fixed by staging a new draft, not by+ promoting.+3. **Preview** — read the draft's files with `canvas-source-retrieve` passing its `version_id`; once+ its build is `ready` the app renders that draft when the version is opened. The draft is **not**+ in `canvas-versions-retrieve` (that lists published history only) and cannot be reverted onto —+ list pending drafts with `canvas-drafts-retrieve`.+4. **Promote** — only when the user approved the draft or explicitly asked to go live; the+ default is to stop after staging and report the draft. `canvas-promote-create` makes the+ draft the live head. Pass+ `expected_current_version_id` (the live `current_version_id` from `canvas-source-retrieve`); it+ is guarded exactly like a publish and 409s on a moved head (recover as below). A draft whose+ build is still `ready` goes live with no rebuild; otherwise a fresh build is queued, so wait for+ it as in step 2. Promote is the only path from a draft to live.+## Recovering from 409 version_conflictA 409 means the canvas moved past your base — a concurrent publish or a revert. The responsediff --git a/products/desktop/packages/core/src/canvas/dashboardSchemas.ts b/products/desktop/packages/core/src/canvas/dashboardSchemas.tsindex 094291d39d59..39e6a1e1f04d 100644--- a/products/desktop/packages/core/src/canvas/dashboardSchemas.ts+++ b/products/desktop/packages/core/src/canvas/dashboardSchemas.ts@@ -1,4 +1,7 @@-import { CANVAS_PLATFORM_MANIFEST } from "@posthog/shared";+import {+ CANVAS_PLATFORM_MANIFEST,+ canvasBuildStatusSchema,+} from "@posthog/shared";import { z } from "zod";// A canvas record from the PostHog canvases API, normalized to camelCase and@@ -42,6 +45,19 @@ export const canvasVersionSchema = z.object({});export type CanvasVersion = z.infer<typeof canvasVersionSchema>;+// A staged draft version and the status of its latest build. Drafts are kept+// out of the published version history (canvasVersionSchema); they are surfaced+// separately so the head/live timeline stays clean.+export const canvasDraftSchema = z.object({+ versionId: z.string(),+ prompt: z.string().nullish(),+ createdBy: z.string().optional(),+ createdAt: z.number(),+ buildStatus: canvasBuildStatusSchema.nullish(),+ buildId: z.string().nullish(),+});+export type CanvasDraft = z.infer<typeof canvasDraftSchema>;+// A canvas source project — the multi-file write format the agent publishes.export const canvasSourceProjectSchema = z.object({schemaVersion: z.number(),@@ -91,6 +107,13 @@ export const revertCanvasInput = z.object({expectedCurrentVersionId: z.string().nullable(),});+// Promote a draft version to the canvas's live head (and build it if needed).+export const promoteCanvasInput = z.object({+ id: z.string().min(1),+ versionId: z.string().min(1),+ expectedCurrentVersionId: z.string().nullable(),+});+// Persist the author-written context (markdown) shown in the Context tab and// passed to generation tasks.export const saveContextInput = z.object({diff --git a/products/desktop/packages/core/src/canvas/dashboardsService.ts b/products/desktop/packages/core/src/canvas/dashboardsService.tsindex d21830ba9502..4ed4f54aee4c 100644--- a/products/desktop/packages/core/src/canvas/dashboardsService.ts+++ b/products/desktop/packages/core/src/canvas/dashboardsService.ts@@ -6,6 +6,7 @@ import {canvasBuildRecordSchema,} from "./canvasBuildSchemas";import type {+ CanvasDraft,CanvasSource,CanvasSourceProject,CanvasVersion,@@ -44,6 +45,15 @@ interface ApiVersion {created_at: string;}+interface ApiDraft {+ version_id: string;+ prompt: string | null;+ created_by?: ApiCanvas["created_by"];+ created_at: string;+ build_status: "queued" | "building" | "ready" | "failed" | null;+ build_id: string | null;+}+function creatorLabel(created_by: ApiCanvas["created_by"]): string | undefined {if (!created_by) return undefined;const name = [created_by.first_name, created_by.last_name]@@ -235,6 +245,44 @@ export class DashboardsService {}));}+ // The canvas's staged drafts, newest first, each with its latest build status.+ async listDrafts(id: string): Promise<CanvasDraft[]> {+ const rows = await this.api.json<ApiDraft[]>(+ `canvases/${encodeURIComponent(id)}/drafts/`,+ "list canvas drafts",+ );+ return rows.map((row) => ({+ versionId: row.version_id,+ prompt: row.prompt,+ createdBy: creatorLabel(row.created_by),+ createdAt: toEpoch(row.created_at) ?? 0,+ buildStatus: row.build_status,+ buildId: row.build_id,+ }));+ }++ // Make a draft version the canvas's live head (adopting its ready build, or+ // rebuilding when the artifacts aged out). Returns the now-live build.+ async promoteDraft(input: {+ id: string;+ versionId: string;+ expectedCurrentVersionId: string | null;+ }): Promise<CanvasBuildRecord> {+ const build = await this.api.json<Record<string, unknown>>(+ `canvases/${encodeURIComponent(input.id)}/promote/`,+ "promote canvas draft",+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ version_id: input.versionId,+ expected_current_version_id: input.expectedCurrentVersionId,+ }),+ },+ );+ return toBuildRecord(build);+ }+// Move the canvas's head back to an existing version and rebuild it.async revertToVersion(input: {id: string;diff --git a/products/desktop/packages/core/src/canvas/generationPrompt.test.ts b/products/desktop/packages/core/src/canvas/generationPrompt.test.tsindex f30e43ec3054..d60d6daf2ae9 100644--- a/products/desktop/packages/core/src/canvas/generationPrompt.test.ts+++ b/products/desktop/packages/core/src/canvas/generationPrompt.test.ts@@ -41,6 +41,20 @@ describe("buildCanvasGenerationPrompt", () => {expect(buildCanvasGenerationPrompt({ ...base, isEdit })).toContain(header);});+ // Guards the draft-by-default contract: an edit to a live canvas must stage+ // a draft the user promotes, never publish straight to the head.+ it.each([+ [false, "`canvas-publish-create`", "`canvas-draft-create`"],+ [true, "`canvas-draft-create`", "`canvas-publish-create`"],+ ])("isEdit=%s saves with the right tool", (isEdit, expected, absent) => {+ const prompt = buildCanvasGenerationPrompt({ ...base, isEdit });+ expect(prompt).toContain(expected);+ expect(prompt).not.toContain(absent);+ if (isEdit) {+ expect(prompt).toContain("promotes it to live");+ }+ });+it.each([["first build with starter", false, true, true],["first build without starter", false, false, false],diff --git a/products/desktop/packages/core/src/canvas/generationPrompt.ts b/products/desktop/packages/core/src/canvas/generationPrompt.tsindex b6cb2fedfd8c..e980ebb1698f 100644--- a/products/desktop/packages/core/src/canvas/generationPrompt.ts+++ b/products/desktop/packages/core/src/canvas/generationPrompt.ts@@ -73,18 +73,30 @@ Do not list or inspect other canvases to choose a target.`;const templateHint = templateId ? TEMPLATE_HINTS[templateId] : undefined;const templateLine = templateHint ? `\n${templateHint}\n` : "";+ // Edits target a canvas people already see live, so they stage a draft the+ // user promotes; only a first build publishes straight to the head.+ const saveBlock = isEdit+ ? `Read the canvas's current source and \`current_version_id\` with the+\`canvas-source-retrieve\` tool before editing. The canvas is live, so stage the COMPLETE+source project as a DRAFT with \`canvas-draft-create\`, wait for its build, and finish by+reporting that the draft is ready — the user previews it and promotes it to live. Do not+publish or promote it yourself unless the user explicitly asked to make the change live.+The canvas lives in PostHog, not on disk — saving happens through those tools. Do not write+local files and do not reply with the code.`+ : `Read the canvas's current source and \`current_version_id\` with the+\`canvas-source-retrieve\` tool before editing, and publish the COMPLETE+source project with \`canvas-publish-create\`, passing that version id as+\`expected_current_version_id\`. The canvas lives in PostHog, not on disk — publishing through+that tool is what saves it. Do not write local files and do not reply with the code.`;+const instructions = `${header}Invoke the \`building-canvases\` skill now and follow its workflow (and the companion canvas-skills it routes to) to implement, validate, and publish this canvas.+skills it routes to) to implement, validate, and save this canvas.${targetBlock}${templateLine}${starterLine}-Read the canvas's current source and \`current_version_id\` with the-\`canvas-source-retrieve\` tool before editing, and publish the COMPLETE-source project with \`canvas-publish-create\`, passing that version id as-\`expected_current_version_id\`. The canvas lives in PostHog, not on disk — publishing through-that tool is what saves it. Do not write local files and do not reply with the code.+${saveBlock}Verify event/property names via the PostHog MCP tools before using them, and operate only onthis project.`;diff --git a/products/desktop/packages/core/src/canvas/services.ts b/products/desktop/packages/core/src/canvas/services.tsindex 061c2bd6cdcb..3ff53de68e27 100644--- a/products/desktop/packages/core/src/canvas/services.ts+++ b/products/desktop/packages/core/src/canvas/services.ts@@ -5,6 +5,7 @@ import type {} from "./canvasBuildSchemas";import type { ChannelTaskRecord } from "./channelTaskSchemas";import type {+ CanvasDraft,CanvasSource,CanvasVersion,DashboardRecord,@@ -51,6 +52,14 @@ export interface IDashboardsService {getSource(input: { id: string; versionId?: string }): Promise<CanvasSource>;// The canvas's source-version history, newest first (metadata only).listVersions(id: string): Promise<CanvasVersion[]>;+ // The canvas's staged drafts, newest first, each with its latest build status.+ listDrafts(id: string): Promise<CanvasDraft[]>;+ // Make a draft version the canvas's live head (and build it if needed).+ promoteDraft(input: {+ id: string;+ versionId: string;+ expectedCurrentVersionId: string | null;+ }): Promise<CanvasBuildRecord>;// Move the canvas's head back to an existing version and rebuild it.revertToVersion(input: {id: string;diff --git a/products/desktop/packages/host-router/src/routers/dashboards.router.ts b/products/desktop/packages/host-router/src/routers/dashboards.router.tsindex 723d084a9375..ea57dbfef2fb 100644--- a/products/desktop/packages/host-router/src/routers/dashboards.router.ts+++ b/products/desktop/packages/host-router/src/routers/dashboards.router.ts@@ -5,6 +5,7 @@ import {} from "@posthog/core/canvas/canvasBuildSchemas";import {canvasBuildsInput,+ canvasDraftSchema,canvasSourceInput,canvasSourceSchema,canvasVersionSchema,@@ -12,6 +13,7 @@ import {dashboardIdInput,dashboardRecordSchema,listDashboardsInput,+ promoteCanvasInput,renameDashboardInput,revertCanvasInput,saveContextInput,@@ -54,6 +56,22 @@ export const dashboardsRouter = router({.get<IDashboardsService>(DASHBOARDS_SERVICE).listVersions(input.id),),+ drafts: publicProcedure+ .input(dashboardIdInput)+ .output(z.array(canvasDraftSchema))+ .query(({ ctx, input }) =>+ ctx.container+ .get<IDashboardsService>(DASHBOARDS_SERVICE)+ .listDrafts(input.id),+ ),+ promoteDraft: publicProcedure+ .input(promoteCanvasInput)+ .output(canvasBuildRecordSchema)+ .mutation(({ ctx, input }) =>+ ctx.container+ .get<IDashboardsService>(DASHBOARDS_SERVICE)+ .promoteDraft(input),+ ),revertToVersion: publicProcedure.input(revertCanvasInput).output(canvasBuildRecordSchema)diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsxindex 06c7434245fa..9996122de842 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsx+++ b/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsx@@ -1,7 +1,9 @@import {ArrowUUpLeftIcon,ArrowUUpRightIcon,+ CaretDownIcon,ClockCounterClockwiseIcon,+ PencilSimpleIcon,ShapesIcon,SidebarSimpleIcon,SpinnerGapIcon,@@ -14,6 +16,7 @@ import {latestFinishedCanvasBuild,publishedCanvasBuild,} from "@posthog/core/canvas/canvasBuildSchemas";+import type { CanvasDraft } from "@posthog/core/canvas/dashboardSchemas";import {type CanvasAnalyticsConfig,type CanvasCommentHighlight,@@ -22,7 +25,12 @@ import {} from "@posthog/core/canvas/freeformSchemas";import { useHostTRPC } from "@posthog/host-router/react";import {+ Badge,Button,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,Empty,EmptyContent,EmptyDescription,@@ -40,6 +48,7 @@ import { invalidateCanvasLifecycle } from "@posthog/ui/features/canvas/hooks/invimport { useCanvasBuilds } from "@posthog/ui/features/canvas/hooks/useCanvasBuilds";import { useChannels } from "@posthog/ui/features/canvas/hooks/useChannels";import {+ useCanvasDrafts,useCanvasSource,useCanvasVersions,useDashboardMutations,@@ -85,6 +94,7 @@ import { canvasCommentTaskId } from "./canvasCommentTask";import { canvasSidePanelVisibility } from "./canvasSidePanelVisibility";import {canvasVersionNavigation,+ freshReadyDraftId,shouldClearCanvasBrowse,} from "./canvasVersionNavigation";import { handleFreeformDataRequest } from "./freeformDataBridge";@@ -108,6 +118,17 @@ function canvasErrorType(message: string): string {);}+// Badge tone for a draft's latest build status: ready is good, failed is bad,+// in-flight is cautionary, and no build yet is neutral.+function draftBadgeVariant(+ status: CanvasDraft["buildStatus"],+): "default" | "warning" | "success" | "destructive" {+ if (status === "ready") return "success";+ if (status === "failed") return "destructive";+ if (status === "queued" || status === "building") return "warning";+ return "default";+}+export function FreeformCanvasView({threadId,interactive,@@ -273,19 +294,80 @@ export function FreeformCanvasView({});// Server-side version history (newest first), for the undo/redo navigation.+ // Drafts are excluded from this list and fetched separately.const { versions, isLoading: versionsLoading } =useCanvasVersions(dashboardId);+ // Drafts drive the Draft-preview/Promote toolbar, which only shows in edit+ // mode; skip the fetch for read-only viewers (who cannot browse a draft).+ const { drafts, isLoading: draftsLoading } = useCanvasDrafts(+ interactive ? dashboardId : undefined,+ );const commentTaskId = canvasCommentTaskId(genTaskId, versions);+ // The browsed version is a draft preview when it matches a staged draft+ // rather than a published version. Drives the Draft label and Promote action.+ const browsingDraft = drafts.some(+ (draft) => draft.versionId === browseVersionId,+ );- // Clear a browse that points at a version the history no longer contains- // (e.g. it was pruned server-side while this canvas was open).+ // Clear a browse that points at a version the canvas no longer offers (e.g.+ // pruned server-side while open). Published versions and drafts are both valid+ // browse targets.useEffect(() => {if (- shouldClearCanvasBrowse({ versions, versionsLoading, browseVersionId })+ shouldClearCanvasBrowse({+ browseTargetIds: [+ ...versions.map((version) => version.id),+ ...drafts.map((draft) => draft.versionId),+ ],+ loading: versionsLoading || draftsLoading,+ browseVersionId,+ })) {setBrowseVersion(threadId, null);}- }, [browseVersionId, versions, versionsLoading, threadId, setBrowseVersion]);+ }, [+ browseVersionId,+ versions,+ drafts,+ versionsLoading,+ draftsLoading,+ threadId,+ setBrowseVersion,+ ]);++ // Auto-open a draft the moment its build finishes, giving a staged draft+ // the same arrival moment a publish has (the canvas swaps when the build+ // lands). The first settled fetch is the baseline, so drafts that were+ // already built don't hijack the view on mount, and each draft opens once.+ const seenReadyDraftIdsRef = useRef<Set<string> | null>(null);+ useEffect(() => {+ if (!interactive) {+ seenReadyDraftIdsRef.current = null;+ return;+ }+ if (draftsLoading) return;+ const readyIds = drafts+ .filter((draft) => draft.buildStatus === "ready")+ .map((draft) => draft.versionId);+ if (seenReadyDraftIdsRef.current === null) {+ seenReadyDraftIdsRef.current = new Set(readyIds);+ return;+ }+ const fresh = freshReadyDraftId(seenReadyDraftIdsRef.current, drafts);+ for (const id of readyIds) {+ seenReadyDraftIdsRef.current.add(id);+ }+ if (fresh && !browseVersionId) {+ setBrowseVersion(threadId, fresh);+ }+ }, [+ interactive,+ drafts,+ draftsLoading,+ browseVersionId,+ threadId,+ setBrowseVersion,+ ]);// Undo/redo step through the version list relative to the HEAD (which, after// a revert, may sit mid-list rather than at versions[0]). The arithmetic is@@ -309,7 +391,8 @@ export function FreeformCanvasView({// Revert: make the browsed version the head. The mutation invalidates the// record, versions, source, and builds caches (the server queues a rebuild),// so afterwards only the local browse state needs clearing.- const { revertToVersion, isReverting } = useDashboardMutations();+ const { revertToVersion, isReverting, promoteDraft, isPromoting } =+ useDashboardMutations();const onRevert = useCallback(async () => {if (!browseVersionId) return;try {@@ -332,6 +415,31 @@ export function FreeformCanvasView({revertToVersion,setBrowseVersion,]);+ // Promote the previewed draft to the live head. Like revert, the mutation+ // refreshes the canvas's lifecycle; afterwards clear the local browse so the+ // view snaps to the now-live version.+ const onPromote = useCallback(async () => {+ if (!browseVersionId) return;+ try {+ await promoteDraft(+ dashboardId,+ browseVersionId,+ dashboard?.currentVersionId ?? null,+ );+ setBrowseVersion(threadId, null);+ } catch (error) {+ toast.error("Couldn't publish draft", {+ description: error instanceof Error ? error.message : String(error),+ });+ }+ }, [+ browseVersionId,+ dashboard?.currentVersionId,+ dashboardId,+ threadId,+ promoteDraft,+ setBrowseVersion,+ ]);// Head source, fetched only when there's no published artifact to render.// Migrated single-file canvases have no version pointer, but the source@@ -595,12 +703,19 @@ export function FreeformCanvasView({><ArrowUUpRightIcon size={16} /></Button>- {versions.length > 0 && (- <Text size="1" className="ml-1 text-gray-9">- v{versions.length - currentIndex}/{versions.length}- </Text>+ {browsingDraft ? (+ <Badge variant="warning" className="ml-1">+ Draft preview+ </Badge>+ ) : (+ versions.length > 0 && (+ <Text size="1" className="ml-1 text-gray-9">+ v{versions.length - currentIndex}/{versions.length}+ {!browsing && " · Live"}+ </Text>+ ))}- {browsing && (+ {browsing && !browsingDraft && (<Buttonsize="sm"variant="primary"@@ -611,6 +726,48 @@ export function FreeformCanvasView({{isReverting ? "Reverting…" : "Revert to this version"}</Button>)}+ {browsingDraft && (+ <Button+ size="sm"+ variant="primary"+ className="ml-1"+ disabled={isPromoting}+ onClick={() => void onPromote()}+ >+ {isPromoting ? "Publishing…" : "Publish draft"}+ </Button>+ )}+ {drafts.length > 0 && (+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button size="sm" variant="default" className="ml-1">+ Drafts ({drafts.length})+ <CaretDownIcon size={12} />+ </Button>+ }+ />+ <DropdownMenuContent align="start" side="bottom">+ {drafts.map((draft) => (+ <DropdownMenuItem+ key={draft.versionId}+ onClick={() =>+ setBrowseVersion(threadId, draft.versionId)+ }+ >+ <span className="mr-2 truncate">+ {draft.prompt || "Untitled draft"}+ </span>+ <Badge+ variant={draftBadgeVariant(draft.buildStatus)}+ >+ {draft.buildStatus ?? "pending"}+ </Badge>+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ )}</>)}</Flex>@@ -696,8 +853,16 @@ export function FreeformCanvasView({className="shrink-0 border-b bg-accent-2 px-3 py-1.5"><Flex align="center" gap="1" className="text-accent-11">- <ClockCounterClockwiseIcon size={14} />- <Text size="1">Viewing a previous version</Text>+ {browsingDraft ? (+ <PencilSimpleIcon size={14} />+ ) : (+ <ClockCounterClockwiseIcon size={14} />+ )}+ <Text size="1">+ {browsingDraft+ ? "Viewing a draft. It isn't live yet."+ : "Viewing a previous version"}+ </Text></Flex><Flex align="center" gap="2"><Button@@ -705,18 +870,28 @@ export function FreeformCanvasView({size="sm"onClick={() => setBrowseVersion(threadId, null)}>- Back to latest+ {browsingDraft ? "Back to live" : "Back to latest"}</Button>- {interactive && (- <Button- size="sm"- variant="primary"- disabled={isReverting}- onClick={() => void onRevert()}- >- {isReverting ? "Reverting…" : "Revert"}- </Button>- )}+ {interactive &&+ (browsingDraft ? (+ <Button+ size="sm"+ variant="primary"+ disabled={isPromoting}+ onClick={() => void onPromote()}+ >+ {isPromoting ? "Publishing…" : "Publish draft"}+ </Button>+ ) : (+ <Button+ size="sm"+ variant="primary"+ disabled={isReverting}+ onClick={() => void onRevert()}+ >+ {isReverting ? "Reverting…" : "Revert"}+ </Button>+ ))}</Flex></Flex><Box className="min-h-0 flex-1">@@ -749,31 +924,43 @@ export function FreeformCanvasView({</EmptyMedia><EmptyTitle>Preview unavailable</EmptyTitle><EmptyDescription>- {interactive- ? "This version does not have a saved preview. Revert to rebuild and view it."- : "This version does not have a saved preview. Go back to the latest version to continue."}+ {browsingDraft+ ? "This draft does not have a preview yet. Publish it to build and make it live."+ : interactive+ ? "This version does not have a saved preview. Revert to rebuild and view it."+ : "This version does not have a saved preview. Go back to the latest version to continue."}</EmptyDescription></EmptyHeader><EmptyContent><Flex align="center" gap="2">- {interactive && (- <Button- variant="primary"- size="default"- disabled={isReverting}- onClick={() => void onRevert()}- >- {isReverting- ? "Reverting…"- : "Revert to this version"}- </Button>- )}+ {interactive &&+ (browsingDraft ? (+ <Button+ variant="primary"+ size="default"+ disabled={isPromoting}+ onClick={() => void onPromote()}+ >+ {isPromoting ? "Publishing…" : "Publish draft"}+ </Button>+ ) : (+ <Button+ variant="primary"+ size="default"+ disabled={isReverting}+ onClick={() => void onRevert()}+ >+ {isReverting+ ? "Reverting…"+ : "Revert to this version"}+ </Button>+ ))}<Buttonvariant="outline"size="default"onClick={() => setBrowseVersion(threadId, null)}>- Back to latest+ {browsingDraft ? "Back to live" : "Back to latest"}</Button></Flex></EmptyContent>diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/canvasVersionNavigation.test.ts b/products/desktop/packages/ui/src/features/canvas/freeform/canvasVersionNavigation.test.tsindex fa4066c65865..34e04b639d2a 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/canvasVersionNavigation.test.ts+++ b/products/desktop/packages/ui/src/features/canvas/freeform/canvasVersionNavigation.test.ts@@ -1,6 +1,7 @@import { describe, expect, it } from "vitest";import {canvasVersionNavigation,+ freshReadyDraftId,shouldClearCanvasBrowse,} from "./canvasVersionNavigation";@@ -113,20 +114,65 @@ describe("canvasVersionNavigation", () => {});});+// Guards the auto-open contract: a draft opens exactly once, when its build+// first turns ready, and never for drafts that were already built (mount) or+// still building.+describe("freshReadyDraftId", () => {+ const seen = new Set(["d-old"]);++ it.each([+ [+ "newly ready draft",+ [{ versionId: "d-new", buildStatus: "ready" }],+ "d-new",+ ],+ [+ "already-seen ready draft",+ [{ versionId: "d-old", buildStatus: "ready" }],+ null,+ ],+ [+ "draft still building",+ [{ versionId: "d-new", buildStatus: "building" }],+ null,+ ],+ [+ "newest fresh draft wins (list is newest first)",+ [+ { versionId: "d-new", buildStatus: "ready" },+ { versionId: "d-older", buildStatus: "ready" },+ ],+ "d-new",+ ],+ ] as const)("%s → %s", (_name, drafts, expected) => {+ expect(freshReadyDraftId(seen, [...drafts])).toBe(expected);+ });+});+describe("shouldClearCanvasBrowse", () => {+ const VERSION_IDS = VERSIONS.map((v) => v.id);+it.each([- ["no browse", null, false, VERSIONS, false],- ["browse still in the list", "v2", false, VERSIONS, false],- ["browse pruned from the list", "vX", false, VERSIONS, true],- ["still loading is not absence", "vX", true, VERSIONS, false],- ["empty list is not absence", "vX", false, [], false],+ ["no browse", null, false, VERSION_IDS, false],+ ["browse still in the list", "v2", false, VERSION_IDS, false],+ ["browse pruned from the list", "vX", false, VERSION_IDS, true],+ ["still loading is not absence", "vX", true, VERSION_IDS, false],+ ["empty targets is not absence", "vX", false, [], false],+ // A staged draft is a valid target even though it is not a published version.+ [+ "draft is a valid target",+ "draft-1",+ false,+ [...VERSION_IDS, "draft-1"],+ false,+ ],] as const)("%s → %s",- (_name, browseVersionId, versionsLoading, versions, expected) => {+ (_name, browseVersionId, loading, browseTargetIds, expected) => {expect(shouldClearCanvasBrowse({- versions: [...versions],- versionsLoading,+ browseTargetIds: [...browseTargetIds],+ loading,browseVersionId,}),).toBe(expected);diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/canvasVersionNavigation.ts b/products/desktop/packages/ui/src/features/canvas/freeform/canvasVersionNavigation.tsindex fab0bad6407b..66627df5449c 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/canvasVersionNavigation.ts+++ b/products/desktop/packages/ui/src/features/canvas/freeform/canvasVersionNavigation.ts@@ -60,20 +60,40 @@ export function canvasVersionNavigation(args: {}/**- * Whether an active browse points at a version the history no longer contains+ * The draft to auto-open: the newest draft whose build is ready and hasn't+ * been seen ready before. Staging a draft is the review-flow counterpart of a+ * publish, which swaps the canvas the moment its build lands; opening the+ * finished draft gives it the same arrival moment instead of leaving it+ * hidden behind the Drafts menu. Returns null when nothing newly finished.+ */+export function freshReadyDraftId(+ seenReady: ReadonlySet<string>,+ drafts: readonly { versionId: string; buildStatus?: string | null }[],+): string | null {+ const fresh = drafts.find(+ (draft) => draft.buildStatus === "ready" && !seenReady.has(draft.versionId),+ );+ return fresh?.versionId ?? null;+}++/**+ * Whether an active browse points at a version the canvas no longer offers* (e.g. it was pruned server-side while the canvas was open) and should be- * cleared. A still-loading or empty history is not evidence of absence.+ * cleared. `browseTargetIds` is every id that is a valid browse target —+ * published versions and staged drafts alike (drafts are a valid preview+ * target even though they are excluded from the published history). A+ * still-loading history is not evidence of absence.*/export function shouldClearCanvasBrowse(args: {- versions: readonly { id: string }[];- versionsLoading: boolean;+ browseTargetIds: readonly string[];+ loading: boolean;browseVersionId: string | null;}): boolean {- const { versions, versionsLoading, browseVersionId } = args;+ const { browseTargetIds, loading, browseVersionId } = args;return (!!browseVersionId &&- !versionsLoading &&- versions.length > 0 &&- !versions.some((v) => v.id === browseVersionId)+ !loading &&+ browseTargetIds.length > 0 &&+ !browseTargetIds.includes(browseVersionId));}diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/invalidateCanvasLifecycle.ts b/products/desktop/packages/ui/src/features/canvas/hooks/invalidateCanvasLifecycle.tsindex 5f5fca124235..2e0f64e8cae0 100644--- a/products/desktop/packages/ui/src/features/canvas/hooks/invalidateCanvasLifecycle.ts+++ b/products/desktop/packages/ui/src/features/canvas/hooks/invalidateCanvasLifecycle.ts@@ -20,6 +20,7 @@ export function invalidateCanvasLifecycle(queryClient.invalidateQueries(trpc.dashboards.get.queryFilter({ id })),queryClient.invalidateQueries(trpc.dashboards.builds.queryFilter({ id })),queryClient.invalidateQueries(trpc.dashboards.versions.queryFilter({ id })),+ queryClient.invalidateQueries(trpc.dashboards.drafts.queryFilter({ id })),queryClient.invalidateQueries(trpc.dashboards.source.queryFilter({ id })),]).then(() => undefined);}diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useDashboards.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useDashboards.tsindex 2cf3fb0b0b40..818e1208de72 100644--- a/products/desktop/packages/ui/src/features/canvas/hooks/useDashboards.ts+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useDashboards.ts@@ -1,5 +1,6 @@import { UNTITLED_CANVAS_NAME } from "@posthog/core/canvas/canvasNaming";import type {+ CanvasDraft,CanvasSource,CanvasVersion,DashboardRecord,@@ -130,6 +131,21 @@ export function useCanvasVersions(id: string | undefined): {return { versions: data ?? [], isLoading };}+/** A canvas's staged drafts, newest first, each with its latest build status. */+export function useCanvasDrafts(id: string | undefined): {+ drafts: CanvasDraft[];+ isLoading: boolean;+} {+ const trpc = useHostTRPC();+ const { data, isLoading } = useQuery(+ trpc.dashboards.drafts.queryOptions(+ { id: id ?? "" },+ { enabled: !!id, staleTime: 5_000 },+ ),+ );+ return { drafts: data ?? [], isLoading };+}+/** Create + delete + metadata mutations, invalidating the list + record. */export function useDashboardMutations() {const trpc = useHostTRPC();@@ -159,6 +175,16 @@ export function useDashboardMutations() {},}),);+ const promoteDraft = useMutation(+ trpc.dashboards.promoteDraft.mutationOptions({+ // Promote makes a draft the head and queues (or adopts) its build, and+ // the version leaves the drafts list for published history — refresh the+ // whole lifecycle (which includes drafts) for that canvas.+ onSuccess: (_data, variables) => {+ void invalidateCanvasLifecycle(queryClient, trpc, variables.id);+ },+ }),+ );const setGenerationTask = useMutation(trpc.dashboards.setGenerationTask.mutationOptions({onSuccess: invalidate,@@ -188,6 +214,12 @@ export function useDashboardMutations() {expectedCurrentVersionId: string | null,) =>revertToVersion.mutateAsync({ id, versionId, expectedCurrentVersionId }),+ // Make a staged draft the canvas's live head (and rebuild it if needed).+ promoteDraft: (+ id: string,+ versionId: string,+ expectedCurrentVersionId: string | null,+ ) => promoteDraft.mutateAsync({ id, versionId, expectedCurrentVersionId }),// Record (or clear) the task generating this canvas. Shared on the canvas// row so every client polling the canvas sees the in-flight generation.setGenerationTask: (id: string, taskId: string | null) =>@@ -204,6 +236,7 @@ export function useDashboardMutations() {isDeleting: remove.isPending,isSavingContext: saveContext.isPending,isReverting: revertToVersion.isPending,+ isPromoting: promoteDraft.isPending,};}diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex f1264a7b2995..b9b1fbe1b7fa 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -1024,8 +1024,36 @@"readOnlyHint": false}},+ "canvas-draft-create": {+ "description": "Build the COMPLETE source project of a canvas as a DRAFT, without changing the live canvas. The project is validated and built server-side exactly like a publish, but the canvas head and live build do NOT move, so viewers keep seeing the current version. For a canvas that already has a live version this is the DEFAULT way to save a change — the user previews and promotes it; use canvas-publish-create only for a first version or when the user explicitly asked to make the change live. Returns the draft's `version_id`, its queued build, and `capability_widening` — how the draft's declared capabilities grow the live version's (insights, capture events, inline queries, network origins) — so added access is visible before shipping. Poll canvas-builds-retrieve until the draft's build is terminal, preview the draft with canvas-source-retrieve passing the returned `version_id`, then make it live with canvas-promote-create. Declare runtime capabilities in `project.capabilities`.",+ "category": "Canvas",+ "feature": "canvas",+ "summary": "Stage a canvas draft build",+ "title": "Stage a canvas draft build",+ "required_scopes": ["canvas:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },+ "canvas-drafts-retrieve": {+ "description": "List a canvas's staged drafts (from canvas-draft-create), newest first, each with its latest build status (queued/building/ready/failed). Drafts are separate from the published version history and are never the live version until promoted. Use this to find a pending draft to preview (canvas-source-retrieve with its `version_id`) and promote (canvas-promote-create).",+ "category": "Canvas",+ "feature": "canvas",+ "summary": "List canvas drafts",+ "title": "List canvas drafts",+ "required_scopes": ["canvas:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"canvas-edit-create": {- "description": "Publish per-file edits against a canvas's current source, without resending the whole project. Each operation sets a file's complete content, or deletes it when `content` is null. `expected_current_version_id` is REQUIRED (from canvas-source-retrieve; null only for a never-published canvas) — a stale base is rejected with 409 version_conflict; re-read the source, re-apply, and edit again. The edited project is validated first; error diagnostics reject the whole edit atomically.",+ "description": "Publish per-file edits against a canvas's current source, without resending the whole project. Each operation sets a file's complete content, or deletes it when `content` is null. `expected_current_version_id` is REQUIRED (from canvas-source-retrieve; null only for a never-published canvas) — a stale base is rejected with 409 version_conflict; re-read the source, re-apply, and edit again. The edited project is validated first; error diagnostics reject the whole edit atomically. Edits go live like a publish — for a canvas with a live version, default to staging the complete project as a draft with canvas-draft-create instead, unless the user asked for an immediate live change.","category": "Canvas","feature": "canvas","summary": "Edit canvas source files",@@ -1052,8 +1080,22 @@"readOnlyHint": true}},+ "canvas-promote-create": {+ "description": "Make a draft version (staged with canvas-draft-create) the canvas's live head. A draft whose build is already ready goes live immediately with no rebuild; otherwise a fresh build is queued. Pass `expected_current_version_id` — the live `current_version_id` from canvas-source-retrieve — so a concurrent change is rejected with 409 version_conflict instead of overwritten. A 429 means the team's build capacity is exhausted; wait and retry. Returns the now-live build. This is the only way a draft reaches the head: revert does not act on drafts.",+ "category": "Canvas",+ "feature": "canvas",+ "summary": "Promote a canvas draft to live",+ "title": "Promote a canvas draft to live",+ "required_scopes": ["canvas:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"canvas-publish-create": {- "description": "Publish the COMPLETE source project of a canvas as its new head version and queue a server-side build. The project is validated first — error diagnostics reject the publish (400) and leave the canvas untouched. Pass `expected_current_version_id` (from canvas-source-retrieve) so a concurrent edit is rejected with 409 version_conflict instead of overwritten; on conflict, re-read the source, re-apply your edits, and publish against the new head. A 429 means the team's build capacity is exhausted — wait a moment and retry. Declare the canvas's runtime capabilities (insights, capture events, inline queries) in `project.capabilities`. The canvas lives in PostHog, not on disk — this tool is what saves it.",+ "description": "Publish the COMPLETE source project of a canvas as its new head version and queue a server-side build. Publishing goes live immediately: use it for a canvas's first version, or when the user explicitly asked to make a change live — otherwise stage the change with canvas-draft-create for the user to promote. The project is validated first — error diagnostics reject the publish (400) and leave the canvas untouched. Pass `expected_current_version_id` (from canvas-source-retrieve) so a concurrent edit is rejected with 409 version_conflict instead of overwritten; on conflict, re-read the source, re-apply your edits, and publish against the new head. A 429 means the team's build capacity is exhausted — wait a moment and retry. Declare the canvas's runtime capabilities (insights, capture events, inline queries) in `project.capabilities`. The canvas lives in PostHog, not on disk — this tool is what saves it.","category": "Canvas","feature": "canvas","summary": "Publish canvas source project",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex b594282bafbc..fa163a3433c7 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -1039,8 +1039,36 @@"readOnlyHint": false}},+ "canvas-draft-create": {+ "description": "Build the COMPLETE source project of a canvas as a DRAFT, without changing the live canvas. The project is validated and built server-side exactly like a publish, but the canvas head and live build do NOT move, so viewers keep seeing the current version. For a canvas that already has a live version this is the DEFAULT way to save a change — the user previews and promotes it; use canvas-publish-create only for a first version or when the user explicitly asked to make the change live. Returns the draft's `version_id`, its queued build, and `capability_widening` — how the draft's declared capabilities grow the live version's (insights, capture events, inline queries, network origins) — so added access is visible before shipping. Poll canvas-builds-retrieve until the draft's build is terminal, preview the draft with canvas-source-retrieve passing the returned `version_id`, then make it live with canvas-promote-create. Declare runtime capabilities in `project.capabilities`.",+ "category": "Canvas",+ "feature": "canvas",+ "summary": "Stage a canvas draft build",+ "title": "Stage a canvas draft build",+ "required_scopes": ["canvas:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },+ "canvas-drafts-retrieve": {+ "description": "List a canvas's staged drafts (from canvas-draft-create), newest first, each with its latest build status (queued/building/ready/failed). Drafts are separate from the published version history and are never the live version until promoted. Use this to find a pending draft to preview (canvas-source-retrieve with its `version_id`) and promote (canvas-promote-create).",+ "category": "Canvas",+ "feature": "canvas",+ "summary": "List canvas drafts",+ "title": "List canvas drafts",+ "required_scopes": ["canvas:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"canvas-edit-create": {- "description": "Publish per-file edits against a canvas's current source, without resending the whole project. Each operation sets a file's complete content, or deletes it when `content` is null. `expected_current_version_id` is REQUIRED (from canvas-source-retrieve; null only for a never-published canvas) — a stale base is rejected with 409 version_conflict; re-read the source, re-apply, and edit again. The edited project is validated first; error diagnostics reject the whole edit atomically.",+ "description": "Publish per-file edits against a canvas's current source, without resending the whole project. Each operation sets a file's complete content, or deletes it when `content` is null. `expected_current_version_id` is REQUIRED (from canvas-source-retrieve; null only for a never-published canvas) — a stale base is rejected with 409 version_conflict; re-read the source, re-apply, and edit again. The edited project is validated first; error diagnostics reject the whole edit atomically. Edits go live like a publish — for a canvas with a live version, default to staging the complete project as a draft with canvas-draft-create instead, unless the user asked for an immediate live change.","category": "Canvas","feature": "canvas","summary": "Edit canvas source files",@@ -1067,8 +1095,22 @@"readOnlyHint": true}},+ "canvas-promote-create": {+ "description": "Make a draft version (staged with canvas-draft-create) the canvas's live head. A draft whose build is already ready goes live immediately with no rebuild; otherwise a fresh build is queued. Pass `expected_current_version_id` — the live `current_version_id` from canvas-source-retrieve — so a concurrent change is rejected with 409 version_conflict instead of overwritten. A 429 means the team's build capacity is exhausted; wait and retry. Returns the now-live build. This is the only way a draft reaches the head: revert does not act on drafts.",+ "category": "Canvas",+ "feature": "canvas",+ "summary": "Promote a canvas draft to live",+ "title": "Promote a canvas draft to live",+ "required_scopes": ["canvas:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"canvas-publish-create": {- "description": "Publish the COMPLETE source project of a canvas as its new head version and queue a server-side build. The project is validated first — error diagnostics reject the publish (400) and leave the canvas untouched. Pass `expected_current_version_id` (from canvas-source-retrieve) so a concurrent edit is rejected with 409 version_conflict instead of overwritten; on conflict, re-read the source, re-apply your edits, and publish against the new head. A 429 means the team's build capacity is exhausted — wait a moment and retry. Declare the canvas's runtime capabilities (insights, capture events, inline queries) in `project.capabilities`. The canvas lives in PostHog, not on disk — this tool is what saves it.",+ "description": "Publish the COMPLETE source project of a canvas as its new head version and queue a server-side build. Publishing goes live immediately: use it for a canvas's first version, or when the user explicitly asked to make a change live — otherwise stage the change with canvas-draft-create for the user to promote. The project is validated first — error diagnostics reject the publish (400) and leave the canvas untouched. Pass `expected_current_version_id` (from canvas-source-retrieve) so a concurrent edit is rejected with 409 version_conflict instead of overwritten; on conflict, re-read the source, re-apply your edits, and publish against the new head. A 429 means the team's build capacity is exhausted — wait a moment and retry. Declare the canvas's runtime capabilities (insights, capture events, inline queries) in `project.capabilities`. The canvas lives in PostHog, not on disk — this tool is what saves it.","category": "Canvas","feature": "canvas","summary": "Publish canvas source project",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 5dacb112d6e6..1e5c8c09b214 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -14251,6 +14251,23 @@ export namespace Schemas {network: CanvasNetworkCapabilities;}+ /**+ * How a draft's declared capabilities grow the current head's. A head that+ * predates the capabilities snapshot reports every declaration as an addition.+ */+ export interface CanvasCapabilityWidening {+ /** True when the draft declares any capability the current head does not. */+ widens: boolean;+ /** Insight short ids the draft newly declares access to. */+ insights_added: string[];+ /** Event names the draft newly declares it may capture. */+ capture_events_added: string[];+ /** True when the draft enables inline queries and the current head does not. */+ inline_queries_enabled: boolean;+ /** Network origins the draft newly declares it may reach. */+ network_origins_added: string[];+ }+/*** Payload for creating a new, empty canvas in a channel.*/@@ -14269,6 +14286,49 @@ export namespace Schemas {template_id?: string;}+ /**+ * A staged draft version and the status of its latest build. Preview a+ * draft's files with `source?version_id=`, then make it live with `promote`.+ */+ export interface CanvasDraft {+ /** Id of the draft source version. */+ version_id: string;+ /**+ * Short description recorded when the draft was staged.+ * @nullable+ */+ prompt: string | null;+ /** Who staged the draft. */+ readonly created_by: UserBasic | null;+ /** When the draft was staged. */+ created_at: string;+ /** Status of the draft's latest build; null when no build has been recorded yet.+ *+ * * `queued` - queued+ * * `building` - building+ * * `ready` - ready+ * * `failed` - failed */+ build_status: BuildStatusEnum | null;+ /**+ * Id of the draft's latest build, when one exists.+ * @nullable+ */+ build_id: string | null;+ }++ /**+ * Payload for promoting a draft version to the canvas's live head.+ */+ export interface CanvasPromote {+ /** Id of the draft source version to make live. */+ version_id: string;+ /**+ * Current source version observed before requesting the promote (null when the canvas has never been published). A moved head is rejected with 409 version_conflict.+ * @nullable+ */+ expected_current_version_id: string | null;+ }+/*** 409 body for a guarded canvas publish based on a stale version.*/@@ -14343,6 +14403,65 @@ export namespace Schemas {content: string;}+ /**+ * Project files keyed by relative path (forward slashes, no '..').+ */+ export type CanvasSourceProjectFiles = {[key: string]: string};++ /**+ * Optional base64-encoded binary assets keyed by safe project-relative paths.+ */+ export type CanvasSourceProjectAssets = {[key: string]: CanvasSourceAsset};++ /**+ * Exact-version dependencies, restricted to the platform-supported set (react, react-dom, @posthog/quill, recharts, lucide-react, dayjs) at their pinned versions.+ */+ export type CanvasSourceProjectDependencies = {[key: string]: string};++ /**+ * A canvas's multi-file source project — the canonical write format for canvas source.+ */+ export interface CanvasSourceProject {+ /** Source-project schema version. Currently always 1. */+ schemaVersion: number;+ /** Project files keyed by relative path (forward slashes, no '..'). */+ files: CanvasSourceProjectFiles;+ /** Optional base64-encoded binary assets keyed by safe project-relative paths. */+ assets?: CanvasSourceProjectAssets;+ /** The project's entry HTML file. Currently always "index.html". */+ entryHtml: string;+ /** Exact-version dependencies, restricted to the platform-supported set (react, react-dom, @posthog/quill, recharts, lucide-react, dayjs) at their pinned versions. */+ dependencies?: CanvasSourceProjectDependencies;+ /** Version of the host-injected `ph` canvas SDK the project targets. */+ canvasSdkVersion?: string;+ /** Bounded capabilities frozen into the built artifact. Declare every insight short id the canvas loads, every event it captures, and inlineQueries when it runs ad-hoc HogQL — the host enforces these at runtime and validation rejects undeclared `ph` calls. */+ capabilities?: CanvasCapabilities;+ }++ /**+ * Payload for staging a complete source project as a draft build.+ */+ export interface CanvasSourceDraft {+ /** The complete source project to stage as a draft. */+ project: CanvasSourceProject;+ /** Short description of the change, stored on the draft's version history entry. */+ prompt?: string;+ }++ /**+ * Result of staging a draft build.+ */+ export interface CanvasSourceDraftResponse {+ /** Id of the draft source version this request created. */+ version_id: string;+ /** The queued draft build; poll `builds` until it is terminal. */+ build: CanvasBuild;+ /** Advisory (warning-severity) diagnostics recorded for the drafted project. */+ diagnostics: CanvasDiagnostic[];+ /** What the draft's declared capabilities grant beyond the current head's. Review before promoting. */+ capability_widening: CanvasCapabilityWidening;+ }+/*** One per-file edit: set a file's content, or delete it.*/@@ -14388,41 +14507,6 @@ export namespace Schemas {diagnostics: CanvasDiagnostic[];}- /**- * Project files keyed by relative path (forward slashes, no '..').- */- export type CanvasSourceProjectFiles = {[key: string]: string};-- /**- * Optional base64-encoded binary assets keyed by safe project-relative paths.- */- export type CanvasSourceProjectAssets = {[key: string]: CanvasSourceAsset};-- /**- * Exact-version dependencies, restricted to the platform-supported set (react, react-dom, @posthog/quill, recharts, lucide-react, dayjs) at their pinned versions.- */- export type CanvasSourceProjectDependencies = {[key: string]: string};-- /**- * A canvas's multi-file source project — the canonical write format for canvas source.- */- export interface CanvasSourceProject {- /** Source-project schema version. Currently always 1. */- schemaVersion: number;- /** Project files keyed by relative path (forward slashes, no '..'). */- files: CanvasSourceProjectFiles;- /** Optional base64-encoded binary assets keyed by safe project-relative paths. */- assets?: CanvasSourceProjectAssets;- /** The project's entry HTML file. Currently always "index.html". */- entryHtml: string;- /** Exact-version dependencies, restricted to the platform-supported set (react, react-dom, @posthog/quill, recharts, lucide-react, dayjs) at their pinned versions. */- dependencies?: CanvasSourceProjectDependencies;- /** Version of the host-injected `ph` canvas SDK the project targets. */- canvasSdkVersion?: string;- /** Bounded capabilities frozen into the built artifact. Declare every insight short id the canvas loads, every event it captures, and inlineQueries when it runs ad-hoc HogQL — the host enforces these at runtime and validation rejects undeclared `ph` calls. */- capabilities?: CanvasCapabilities;- }-/*** Payload for publishing a complete canvas source project.*/@@ -14534,6 +14618,8 @@ export namespace Schemas {* @nullable*/task_id: string | null;+ /** True for a staged draft version that has never been the canvas head; promote it to make it live. */+ draft: boolean;readonly created_by: UserBasic | null;/** When the version was published. */created_at: string;@@ -46906,6 +46992,15 @@ export namespace Schemas {results: CIMDVerificationToken[];}+ export interface PaginatedCanvasDraftList {+ count: number;+ /** @nullable */+ next?: string | null;+ /** @nullable */+ previous?: string | null;+ results: CanvasDraft[];+ }+export interface PaginatedCanvasList {count: number;/** @nullable */@@ -81409,6 +81504,17 @@ export namespace Schemas {version_id?: string;};+ export type CanvasesDraftsRetrieveParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number;+ /**+ * The initial index from which to return the results.+ */+ offset?: number;+ };+export type CanvasesSourceRetrieveParams = {/*** Read this historical source version instead of the head (for version browsing).diff --git a/services/mcp/src/generated/canvas/api.ts b/services/mcp/src/generated/canvas/api.tsindex df752151e21b..64f303f03c4c 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 7 enabled ops+ * PostHog API - MCP 10 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -79,6 +79,152 @@ export const CanvasesBuildsRetrieveQueryParams = /* @__PURE__ */ zod.object({.describe('Include the retained ready build for this historical source version.'),})+/**+ * Stage a complete source project as a draft version and build it, without publishing.+ *+ * The draft gets the same validation, versioning, and server-side build as+ * a publish, but the canvas's head and live build never move, so nothing+ * changes for viewers. Promote the version with `promote` to make it live.+ * The response reports how the draft's declared capabilities widen the+ * current head's, so growth in access can be reviewed before it ships.+ * No version guard applies: a draft conflicts with nothing.+ */+export const CanvasesDraftCreateParams = /* @__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 canvasesDraftCreateBodyProjectOneAssetsContentMax = 2796204++export const canvasesDraftCreateBodyProjectOneAssetsContentRegExp = new RegExp(+ '^(?:[A-Za-z0-9+\/]{4})\*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$'+)+export const canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogInsightsItemMax = 128++export const canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogInsightsMax = 100++export const canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogCaptureEventsItemMax = 200++export const canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogCaptureEventsMax = 100++export const canvasesDraftCreateBodyProjectOneCapabilitiesOneNetworkOriginsItemMax = 2048++export const canvasesDraftCreateBodyProjectOneCapabilitiesOneNetworkOriginsMax = 20++export const CanvasesDraftCreateBody = /* @__PURE__ */ zod+ .object({+ project: zod+ .object({+ schemaVersion: zod.number().describe('Source-project schema version. Currently always 1.'),+ files: zod+ .record(zod.string(), zod.string())+ .describe("Project files keyed by relative path (forward slashes, no '..')."),+ assets: zod+ .record(+ zod.string(),+ zod.object({+ encoding: zod.enum(['base64']).describe('\* `base64` - base64'),+ contentType: zod+ .enum([+ 'image/png',+ 'image/jpeg',+ 'image/gif',+ 'image/webp',+ 'image/svg+xml',+ 'font/woff',+ 'font/woff2',+ 'application/wasm',+ 'application/octet-stream',+ ])+ .describe(+ '\* `image\/png` - image\/png\n\* `image\/jpeg` - image\/jpeg\n\* `image\/gif` - image\/gif\n\* `image\/webp` - image\/webp\n\* `image\/svg+xml` - image\/svg+xml\n\* `font\/woff` - font\/woff\n\* `font\/woff2` - font\/woff2\n\* `application\/wasm` - application\/wasm\n\* `application\/octet-stream` - application\/octet-stream'+ ),+ content: zod+ .string()+ .max(canvasesDraftCreateBodyProjectOneAssetsContentMax)+ .regex(canvasesDraftCreateBodyProjectOneAssetsContentRegExp),+ })+ )+ .optional()+ .describe('Optional base64-encoded binary assets keyed by safe project-relative paths.'),+ entryHtml: zod.string().describe('The project\'s entry HTML file. Currently always \"index.html\".'),+ dependencies: zod+ .record(zod.string(), zod.string())+ .optional()+ .describe(+ 'Exact-version dependencies, restricted to the platform-supported set (react, react-dom, @posthog\/quill, recharts, lucide-react, dayjs) at their pinned versions.'+ ),+ canvasSdkVersion: zod+ .string()+ .optional()+ .describe('Version of the host-injected `ph` canvas SDK the project targets.'),+ capabilities: zod+ .object({+ posthog: zod.object({+ insights: zod+ .array(+ zod+ .string()+ .max(canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogInsightsItemMax)+ )+ .max(canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogInsightsMax),+ inlineQueries: zod.boolean(),+ captureEvents: zod+ .array(+ zod+ .string()+ .max(+ canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogCaptureEventsItemMax+ )+ )+ .max(canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogCaptureEventsMax),+ }),+ network: zod.object({+ origins: zod+ .array(+ zod.url().max(canvasesDraftCreateBodyProjectOneCapabilitiesOneNetworkOriginsItemMax)+ )+ .max(canvasesDraftCreateBodyProjectOneCapabilitiesOneNetworkOriginsMax),+ }),+ })+ .optional()+ .describe(+ 'Bounded capabilities frozen into the built artifact. Declare every insight short id the canvas loads, every event it captures, and inlineQueries when it runs ad-hoc HogQL — the host enforces these at runtime and validation rejects undeclared `ph` calls.'+ ),+ })+ .describe("A canvas's multi-file source project — the canonical write format for canvas source.")+ .describe('The complete source project to stage as a draft.'),+ prompt: zod+ .string()+ .optional()+ .describe("Short description of the change, stored on the draft's version history entry."),+ })+ .describe('Payload for staging a complete source project as a draft build.')++/**+ * The canvas's staged draft versions, newest first, each with its latest build status.+ *+ * A draft is a version that was built but never made the head. Preview one+ * with `source?version_id=`, then make it live with `promote`.+ */+export const CanvasesDraftsRetrieveParams = /* @__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 CanvasesDraftsRetrieveQueryParams = /* @__PURE__ */ zod.object({+ limit: zod.number().optional().describe('Number of results to return per page.'),+ offset: zod.number().optional().describe('The initial index from which to return the results.'),+})+/*** Publish per-file edits against the canvas's current source project.*@@ -136,6 +282,33 @@ export const CanvasesEditCreateBody = /* @__PURE__ */ zod}).describe("Payload for publishing per-file edits against the canvas's current source.")+/**+ * Make a draft version the canvas's live head.+ *+ * A draft whose build is ready goes live immediately, with no rebuild;+ * otherwise a fresh build is queued. Returns that build.+ */+export const CanvasesPromoteCreateParams = /* @__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 CanvasesPromoteCreateBody = /* @__PURE__ */ zod+ .object({+ version_id: zod.string().describe('Id of the draft source version to make live.'),+ expected_current_version_id: zod+ .string()+ .nullable()+ .describe(+ 'Current source version observed before requesting the promote (null when the canvas has never been published). A moved head is rejected with 409 version_conflict.'+ ),+ })+ .describe("Payload for promoting a draft version to the canvas's live head.")+/*** Publish a complete source project as the canvas's new head version.*diff --git a/services/mcp/src/tools/generated/canvas.ts b/services/mcp/src/tools/generated/canvas.tsindex 4a69492fb195..a9a46d1752ad 100644--- a/services/mcp/src/tools/generated/canvas.ts+++ b/services/mcp/src/tools/generated/canvas.ts@@ -6,9 +6,15 @@ import {CanvasesBuildsRetrieveParams,CanvasesBuildsRetrieveQueryParams,CanvasesCreateBody,+ CanvasesDraftCreateBody,+ CanvasesDraftCreateParams,+ CanvasesDraftsRetrieveParams,+ CanvasesDraftsRetrieveQueryParams,CanvasesEditCreateBody,CanvasesEditCreateParams,CanvasesListQueryParams,+ CanvasesPromoteCreateBody,+ CanvasesPromoteCreateParams,CanvasesPublishCreateBody,CanvasesPublishCreateParams,CanvasesSourceRetrieveParams,@@ -40,7 +46,7 @@ const canvasBuildsRetrieve = (): ToolBase<typeof CanvasBuildsRetrieveSchema, Schconst CanvasCreateSchema = CanvasesCreateBody.extend({channel_id: CanvasesCreateBody.shape['channel_id'].describe(- 'Id of the channel to create the canvas in (resolve it with channel-list).'+ "Id of the channel to create the canvas in — the channel the task was created in, from the task's context. Use channel-list only to resolve a channel the user named; never pick a channel from the listing yourself (the personal #me channel is not a default)."),})@@ -68,6 +74,52 @@ const canvasCreate = (): ToolBase<typeof CanvasCreateSchema, Schemas.Canvas> =>},})+const CanvasDraftCreateSchema = CanvasesDraftCreateParams.omit({ project_id: true })+ .extend(CanvasesDraftCreateBody.shape)+ .extend({ id: CanvasesDraftCreateParams.shape['id'].describe('ID of the canvas to stage a draft for.') })++const canvasDraftCreate = (): ToolBase<typeof CanvasDraftCreateSchema, Schemas.CanvasSourceDraftResponse> => ({+ name: 'canvas-draft-create',+ schema: CanvasDraftCreateSchema,+ handler: async (context: Context, params: z.infer<typeof CanvasDraftCreateSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.project !== undefined) {+ body['project'] = params.project+ }+ if (params.prompt !== undefined) {+ body['prompt'] = params.prompt+ }+ const result = await context.api.request<Schemas.CanvasSourceDraftResponse>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/canvases/${encodeURIComponent(String(params.id))}/draft/`,+ body,+ })+ return result+ },+})++const CanvasDraftsRetrieveSchema = CanvasesDraftsRetrieveParams.omit({ project_id: true })+ .extend(CanvasesDraftsRetrieveQueryParams.shape)+ .extend({ id: CanvasesDraftsRetrieveParams.shape['id'].describe('ID of the canvas whose drafts to list.') })++const canvasDraftsRetrieve = (): ToolBase<typeof CanvasDraftsRetrieveSchema, Schemas.PaginatedCanvasDraftList> => ({+ name: 'canvas-drafts-retrieve',+ schema: CanvasDraftsRetrieveSchema,+ handler: async (context: Context, params: z.infer<typeof CanvasDraftsRetrieveSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.PaginatedCanvasDraftList>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/canvases/${encodeURIComponent(String(params.id))}/drafts/`,+ query: {+ limit: params.limit,+ offset: params.offset,+ },+ })+ return result+ },+})+const CanvasEditCreateSchema = CanvasesEditCreateParams.omit({ project_id: true }).extend(CanvasesEditCreateBody.shape).extend({ id: CanvasesEditCreateParams.shape['id'].describe('ID of the canvas whose source to edit.') })@@ -121,6 +173,31 @@ const canvasList = (): ToolBase<typeof CanvasListSchema, Schemas.PaginatedCanvas},})+const CanvasPromoteCreateSchema = CanvasesPromoteCreateParams.omit({ project_id: true })+ .extend(CanvasesPromoteCreateBody.shape)+ .extend({ id: CanvasesPromoteCreateParams.shape['id'].describe('ID of the canvas whose draft to promote.') })++const canvasPromoteCreate = (): ToolBase<typeof CanvasPromoteCreateSchema, Schemas.CanvasBuild> => ({+ name: 'canvas-promote-create',+ schema: CanvasPromoteCreateSchema,+ handler: async (context: Context, params: z.infer<typeof CanvasPromoteCreateSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.version_id !== undefined) {+ body['version_id'] = params.version_id+ }+ 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))}/promote/`,+ body,+ })+ return result+ },+})+const CanvasPublishCreateSchema = CanvasesPublishCreateParams.omit({ project_id: true }).extend(CanvasesPublishCreateBody.shape).extend({ id: CanvasesPublishCreateParams.shape['id'].describe('ID of the canvas whose source to publish.') })@@ -197,8 +274,11 @@ const canvasValidateCreate = (): ToolBase<typeof CanvasValidateCreateSchema, Schexport const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'canvas-builds-retrieve': canvasBuildsRetrieve,'canvas-create': canvasCreate,+ 'canvas-draft-create': canvasDraftCreate,+ 'canvas-drafts-retrieve': canvasDraftsRetrieve,'canvas-edit-create': canvasEditCreate,'canvas-list': canvasList,+ 'canvas-promote-create': canvasPromoteCreate,'canvas-publish-create': canvasPublishCreate,'canvas-source-retrieve': canvasSourceRetrieve,'canvas-validate-create': canvasValidateCreate,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-create.jsonindex b508c82437ca..f94c23b6298d 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-create.json@@ -2,7 +2,7 @@"$schema": "https://json-schema.org/draft/2020-12/schema","properties": {"channel_id": {- "description": "Id of the channel to create the canvas in (resolve it with channel-list).",+ "description": "Id of the channel to create the canvas in — the channel the task was created in, from the task's context. Use channel-list only to resolve a channel the user named; never pick a channel from the listing yourself (the personal #me channel is not a default).","type": "string"},"name": {diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-draft-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-draft-create.jsonnew file mode 100644index 000000000000..e119da26d546--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-draft-create.json@@ -0,0 +1,139 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "id": {+ "description": "ID of the canvas to stage a draft for.",+ "type": "string"+ },+ "project": {+ "description": "The complete source project to stage as a draft.",+ "properties": {+ "assets": {+ "additionalProperties": {+ "properties": {+ "content": {+ "maxLength": 2796204,+ "pattern": "^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$",+ "type": "string"+ },+ "contentType": {+ "description": "* `image/png` - image/png\n* `image/jpeg` - image/jpeg\n* `image/gif` - image/gif\n* `image/webp` - image/webp\n* `image/svg+xml` - image/svg+xml\n* `font/woff` - font/woff\n* `font/woff2` - font/woff2\n* `application/wasm` - application/wasm\n* `application/octet-stream` - application/octet-stream",+ "enum": [+ "image/png",+ "image/jpeg",+ "image/gif",+ "image/webp",+ "image/svg+xml",+ "font/woff",+ "font/woff2",+ "application/wasm",+ "application/octet-stream"+ ],+ "type": "string"+ },+ "encoding": {+ "description": "* `base64` - base64",+ "enum": ["base64"],+ "type": "string"+ }+ },+ "required": ["encoding", "contentType", "content"],+ "type": "object"+ },+ "description": "Optional base64-encoded binary assets keyed by safe project-relative paths.",+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ "canvasSdkVersion": {+ "description": "Version of the host-injected `ph` canvas SDK the project targets.",+ "type": "string"+ },+ "capabilities": {+ "description": "Bounded capabilities frozen into the built artifact. Declare every insight short id the canvas loads, every event it captures, and inlineQueries when it runs ad-hoc HogQL — the host enforces these at runtime and validation rejects undeclared `ph` calls.",+ "properties": {+ "network": {+ "properties": {+ "origins": {+ "items": {+ "format": "uri",+ "maxLength": 2048,+ "type": "string"+ },+ "maxItems": 20,+ "type": "array"+ }+ },+ "required": ["origins"],+ "type": "object"+ },+ "posthog": {+ "properties": {+ "captureEvents": {+ "items": {+ "maxLength": 200,+ "type": "string"+ },+ "maxItems": 100,+ "type": "array"+ },+ "inlineQueries": {+ "type": "boolean"+ },+ "insights": {+ "items": {+ "maxLength": 128,+ "type": "string"+ },+ "maxItems": 100,+ "type": "array"+ }+ },+ "required": ["insights", "inlineQueries", "captureEvents"],+ "type": "object"+ }+ },+ "required": ["posthog", "network"],+ "type": "object"+ },+ "dependencies": {+ "additionalProperties": {+ "type": "string"+ },+ "description": "Exact-version dependencies, restricted to the platform-supported set (react, react-dom, @posthog/quill, recharts, lucide-react, dayjs) at their pinned versions.",+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ "entryHtml": {+ "description": "The project's entry HTML file. Currently always \"index.html\".",+ "type": "string"+ },+ "files": {+ "additionalProperties": {+ "type": "string"+ },+ "description": "Project files keyed by relative path (forward slashes, no '..').",+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ "schemaVersion": {+ "description": "Source-project schema version. Currently always 1.",+ "type": "number"+ }+ },+ "required": ["schemaVersion", "files", "entryHtml"],+ "type": "object"+ },+ "prompt": {+ "description": "Short description of the change, stored on the draft's version history entry.",+ "type": "string"+ }+ },+ "required": ["id", "project"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-drafts-retrieve.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-drafts-retrieve.jsonnew file mode 100644index 000000000000..df5226db6cba--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-drafts-retrieve.json@@ -0,0 +1,19 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "id": {+ "description": "ID of the canvas whose drafts to list.",+ "type": "string"+ },+ "limit": {+ "description": "Number of results to return per page.",+ "type": "number"+ },+ "offset": {+ "description": "The initial index from which to return the results.",+ "type": "number"+ }+ },+ "required": ["id"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-promote-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-promote-create.jsonnew file mode 100644index 000000000000..032e7e616a33--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-promote-create.json@@ -0,0 +1,26 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "expected_current_version_id": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Current source version observed before requesting the promote (null when the canvas has never been published). A moved head is rejected with 409 version_conflict."+ },+ "id": {+ "description": "ID of the canvas whose draft to promote.",+ "type": "string"+ },+ "version_id": {+ "description": "Id of the draft source version to make live.",+ "type": "string"+ }+ },+ "required": ["id", "version_id", "expected_current_version_id"],+ "type": "object"+}