: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): publish by default and let space members edit canvases (#94530)
Peter Kirkham8a970e1348c2
diff --git a/docs/internal/canvas-collaboration.md b/docs/internal/canvas-collaboration.mdnew file mode 100644index 000000000000..ee042ed3951b--- /dev/null+++ b/docs/internal/canvas-collaboration.md@@ -0,0 +1,46 @@+# Canvas collaboration++## Access++Signed-in project members can edit canvases in public spaces. A task-bound sandbox+with an authenticated user has the same content access. It must use its bound task ID.+Personal-space canvases remain private to their owner. Team boundaries do not change.++Members can publish source, edit files, rebuild the current version, stage drafts,+promote drafts, and revert versions. They can also edit canvas context and record+their own generation task. Only the canvas creator can rename, move, pin, describe,+or delete the canvas. The publish and edit endpoints reject a non-creator's `name`+field with HTTP 403, without saving source or changing the current version.++## Publishing and recovery++Agent runs publish by default. Ask for a draft or a review step to keep a change+off the live canvas. A publish creates a source version and queues its build.+The live artifact changes only after a successful build. A failed build leaves+the last successful artifact available.++Use `expected_current_version_id` when publishing. A stale version returns HTTP 409.+Read the current source, apply the change again, and retry against that version.+Use version history to inspect earlier source and revert an unwanted change.+Version history shows the publisher and links to the publishing task without+assuming that the task belongs to the canvas's current space.++## Agent sessions++The canvas panel shows the active run's chat. After the run finishes, edit mode+shows a new composer. View mode shows an empty chat state. Comments remain attached+to the earlier task. Each new edit starts a new task and session.++## Release checks++The desktop changes use existing endpoints and version fields. They can ship before+or after the backend changes. The backend still controls write access. An older+backend continues to reject shared edits until the new permissions reach it.++Check shared edits with both a signed-in member and a task-bound sandbox. Confirm+that name changes fail for non-creators, personal-space access stays private, and+stale publishes return HTTP 409. Confirm that a finished run returns to the composer+and that a version's task link does not use the canvas's space ID.++Use the existing `canvas published` events and canvas build results to check publish+activity and failures after release. No new analytics events are required.diff --git a/products/canvas/backend/error_reports.py b/products/canvas/backend/error_reports.pyindex 595f791f7d05..4daaf9673768 100644--- a/products/canvas/backend/error_reports.py+++ b/products/canvas/backend/error_reports.py@@ -135,18 +135,19 @@ def build_fix_prompt(f"{what}\n\n""Invoke the `building-canvases` skill and follow its workflow. Read the current source with "f"`canvas-source-retrieve`. {context}\n\n"- "Stage the fix as a DRAFT with `canvas-draft-create` and wait for its build to be ready. "- "Do not publish or promote anything: the user reviews the draft and promotes it."+ "Publish the fix with `canvas-edit-create` (or `canvas-publish-create` for the complete project) against "+ "the current version, then wait for its build to be ready. Stage a draft instead only if the user asked "+ "for one.")def build_agent_request_prompt(canvas: Canvas, prompt: str) -> str:- """Wrap the viewer-approved request with the canvas draft workflow."""+ """Wrap the viewer-approved request with the canvas publish workflow."""return (f"A viewer requested a change to canvas {canvas.id}.\n\n"f"<canvas-change-request>\n{prompt}\n</canvas-change-request>\n\n""Invoke the `building-canvases` skill and follow its workflow. Read the current source with "- "`canvas-source-retrieve`. Stage the requested change as a DRAFT with `canvas-draft-create` and wait for "- "its build to be ready. Do not publish or promote anything: the canvas creator reviews the draft and "- "promotes it."+ "`canvas-source-retrieve`. Publish the requested change with `canvas-edit-create` (or "+ "`canvas-publish-create` for the complete project) against the current version, then wait for its build "+ "to be ready. Stage a draft instead only if the request asks for one.")diff --git a/products/canvas/backend/presentation/views.py b/products/canvas/backend/presentation/views.pyindex 966d62b47105..8615306be478 100644--- a/products/canvas/backend/presentation/views.py+++ b/products/canvas/backend/presentation/views.py@@ -188,6 +188,7 @@ class CanvasAccessMixin(TeamAndOrgViewSetMixin):"""Team, channel, and sandbox visibility rules shared by every canvas-like resource."""scope_object_read_actions: list[str] = []+ _EDITOR_ACTIONS: set[str] = set()def safely_get_queryset(self, queryset: QuerySet) -> QuerySet:queryset = queryset.filter(team_id=self.team_id, deleted=False)@@ -206,7 +207,11 @@ class CanvasAccessMixin(TeamAndOrgViewSetMixin):)else:actor_canvas_q = Q(created_by_id=user.id) & tasks_facade.visible_channels_q(user.id, relation="channel")- can_use_visible_canvas = self.action in [*self.scope_object_read_actions, "set_state"]+ can_use_visible_canvas = self.action in [+ *self.scope_object_read_actions,+ "set_state",+ *self._EDITOR_ACTIONS,+ ]queryset = queryset.filter(public_canvas_q | actor_canvas_q if can_use_visible_canvas else actor_canvas_q)@@ -339,10 +344,15 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.ModelViewSet):return Nonereturn ["canvas:write", *entry.required_scopes]- _CREATOR_ONLY_ACTIONS = {+ # Content writes. Every member who can see a canvas in a public space may+ # publish a new version of it; a canvas in a personal space is only visible+ # to its owner, so the creator rule is implied there. partial_update is in+ # this set because a member must record their own generation task on the+ # canvas; the other metadata fields stay creator-only (see partial_update).+ _EDITOR_ACTIONS = {"partial_update",- "destroy","publish",+ "publish_current_version","edit","draft","promote",@@ -351,6 +361,8 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.ModelViewSet):"publish_layout","patch_layout",}+ _CREATOR_ONLY_ACTIONS = {"destroy"}+ _NON_CREATOR_UPDATE_FIELDS = {"generation_task_id", "context"}@extend_schema(parameters=[@@ -379,6 +391,12 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.ModelViewSet):queryset = super().safely_get_queryset(queryset).filter(source_policy=Canvas.SOURCE_POLICY_STANDARD)user = self._request_user()is_sandbox_authenticated = self._is_sandbox_authenticated(self.request)+ if not is_sandbox_authenticated and self.action in self._EDITOR_ACTIONS:+ if user is None:+ return queryset.none()+ queryset = queryset.filter(+ Q(created_by_id=user.id) | tasks_facade.visible_channels_q(None, relation="channel")+ )if not is_sandbox_authenticated and self.action in self._CREATOR_ONLY_ACTIONS:if user is None:return queryset.none()@@ -448,7 +466,12 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.ModelViewSet):@extend_schema(operation_id="canvases_partial_update",request=CanvasUpdateSerializer,- responses={200: CanvasSerializer},+ responses={+ 200: CanvasSerializer,+ 403: OpenApiResponse(+ description="Only the canvas creator can change the name, description, space, or pin state."+ ),+ },)def partial_update(self, request: Request, *args: Any, **kwargs: Any) -> Response:"""Update canvas metadata, including the space it belongs to."""@@ -456,6 +479,13 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.ModelViewSet):payload = CanvasUpdateSerializer(data=request.data)payload.is_valid(raise_exception=True)data = payload.validated_data+ requester = self._request_user()+ is_creator = requester is not None and canvas.created_by_id == requester.id+ if not is_creator and set(data) - self._NON_CREATOR_UPDATE_FIELDS:+ return Response(+ {"detail": "Only the canvas creator can rename, move, pin, or describe it."},+ status=status.HTTP_403_FORBIDDEN,+ )update_fields = ["updated_at"]changes: list[Change] = []@@ -656,6 +686,7 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.ModelViewSet):request=CanvasSourcePublishSerializer,responses={200: CanvasSourcePublishResponseSerializer,+ 403: OpenApiResponse(description="Only the canvas creator can supply a name when publishing."),400: OpenApiResponse(response=CanvasSourceInvalidSerializer,description="The source project failed validation.",@@ -696,6 +727,7 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.ModelViewSet):request=CanvasSourceEditSerializer,responses={200: CanvasSourcePublishResponseSerializer,+ 403: OpenApiResponse(description="Only the canvas creator can supply a name when editing."),400: OpenApiResponse(response=CanvasSourceInvalidSerializer,description="An edit targeted a missing file, or the edited project failed validation.",@@ -763,11 +795,14 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.ModelViewSet):has_expected_version: bool,expected_version_id: str | None,) -> Response:+ user = self._request_user()+ if name is not None and (user is None or canvas.created_by_id != user.id):+ raise PermissionDenied("Only the canvas creator can rename it.")+diagnostics = validate_source_project(project, kind=canvas.kind)if has_errors(diagnostics):return _invalid_response(diagnostics)- user = self._request_user()task_id = self._sandbox_task_id(request)try:canvas, version, _build, first_publish = build_service.publish_source_project(diff --git a/products/canvas/backend/tests/test_canvas_api.py b/products/canvas/backend/tests/test_canvas_api.pyindex 3765b463ef7e..a17fbf45f72e 100644--- a/products/canvas/backend/tests/test_canvas_api.py+++ b/products/canvas/backend/tests/test_canvas_api.py@@ -276,6 +276,34 @@ class TestCanvasCrud(CanvasAPIBaseTest):assert self.client.post(f"{base}/publish/", {"project": self._project()}, format="json").status_code == 404assert self.client.delete(f"{base}/").status_code == 404+ def test_public_space_member_can_publish_but_not_manage_another_creators_canvas(self):+ canvas_id = self._create_canvas(name="Shared canvas")+ other_user = self._create_user("[email protected]")+ own_task = Task.objects.create(+ team=self.team,+ channel=self.channel,+ created_by=other_user,+ title="Edit shared canvas",+ description="d",+ origin_product=Task.OriginProduct.USER_CREATED,+ )+ self.client.force_login(other_user)+ base = f"/api/projects/{self.team.id}/canvases/{canvas_id}"++ publish = self.client.post(f"{base}/publish/", {"project": self._project()}, format="json")+ assert publish.status_code == status.HTTP_200_OK+ version = CanvasSourceVersion.objects.unscoped().get(id=publish.json()["current_version_id"])+ assert version.created_by_id == other_user.id++ track_task = self.client.patch(f"{base}/", {"generation_task_id": str(own_task.id)}, format="json")+ assert track_task.status_code == status.HTTP_200_OK+ assert track_task.json()["generation_task_id"] == str(own_task.id)++ assert self.client.patch(f"{base}/", {"name": "Renamed"}, format="json").status_code == 403+ assert self.client.patch(f"{base}/", {"pinned": True}, format="json").status_code == 403+ assert self.client.delete(f"{base}/").status_code == 404+ assert Canvas.objects.unscoped().get(id=canvas_id).name == "Shared canvas"+def test_task_bound_sandbox_can_create_only_for_its_bound_task(self):bound_task = Task.objects.create(team=self.team,@@ -384,7 +412,7 @@ class TestCanvasCrud(CanvasAPIBaseTest):assert earlier_detail.status_code == status.HTTP_200_OKassert update.status_code == status.HTTP_200_OKassert update.json()["name"] == "Updated by later task"- assert linked_update.status_code == status.HTTP_404_NOT_FOUND+ assert linked_update.status_code == status.HTTP_403_FORBIDDENdef test_rebound_sandbox_does_not_inherit_task_creator_canvas_access(self) -> None:actor = self._create_user("[email protected]")@@ -433,7 +461,7 @@ class TestCanvasCrud(CanvasAPIBaseTest):)assert public_read.status_code == status.HTTP_200_OK- assert public_write.status_code == status.HTTP_404_NOT_FOUND+ assert public_write.status_code == status.HTTP_403_FORBIDDENassert personal_read.status_code == status.HTTP_404_NOT_FOUNDdef test_rebound_sandbox_can_write_canvas_created_by_actor(self) -> None:@@ -474,7 +502,7 @@ class TestCanvasCrud(CanvasAPIBaseTest):assert update_response.json()["name"] == "Updated by actor"assert publish_response.status_code == status.HTTP_200_OK- def test_task_bound_sandbox_can_read_but_not_write_another_creators_public_canvas(self):+ def test_task_bound_sandbox_can_publish_but_not_rename_another_creators_public_canvas(self):other_user = self._create_user("[email protected]")bound_task = Task.objects.create(team=self.team,@@ -496,15 +524,34 @@ class TestCanvasCrud(CanvasAPIBaseTest):f"/api/projects/{self.team.id}/canvases/{other_canvas.id}/",HTTP_X_POSTHOG_TASK_ID=str(bound_task.id),)- write_response = client.patch(+ rename_response = client.patch(f"/api/projects/{self.team.id}/canvases/{other_canvas.id}/",{"name": "Not allowed"},format="json",HTTP_X_POSTHOG_TASK_ID=str(bound_task.id),)+ publish_response = client.post(+ f"/api/projects/{self.team.id}/canvases/{other_canvas.id}/publish/",+ {"project": self._project()},+ format="json",+ HTTP_X_POSTHOG_TASK_ID=str(bound_task.id),+ )assert read_response.status_code == status.HTTP_200_OK- assert write_response.status_code == status.HTTP_404_NOT_FOUND+ assert rename_response.status_code == status.HTTP_403_FORBIDDEN+ assert publish_response.status_code == status.HTTP_200_OK+ version = CanvasSourceVersion.objects.unscoped().get(id=publish_response.json()["current_version_id"])+ assert version.created_by_id == self.user.id+ assert version.task_id == bound_task.id++ rebuild_response = client.post(+ f"/api/projects/{self.team.id}/canvases/{other_canvas.id}/publish-current-version/",+ {"expected_current_version_id": str(version.id)},+ format="json",+ HTTP_X_POSTHOG_TASK_ID=str(bound_task.id),+ )+ assert rebuild_response.status_code == status.HTTP_200_OK, rebuild_response.json()+ assert rebuild_response.json()["source_version_id"] == str(version.id)def test_personal_space_sandbox_can_read_authenticated_users_canvas(self):with team_scope(self.team.id):@@ -692,15 +739,44 @@ class TestCanvasSourceAndPublish(CanvasAPIBaseTest):assert body["current_version_id"] == version_idassert body["project"]["files"]["src/extra.ts"] == "export const x = 1"- def test_public_members_can_publish_current_source_but_cannot_edit(self):+ @parameterized.expand([("member", False), ("sandbox", True)])+ def test_public_members_can_edit_and_publish_but_not_rename(self, _name: str, sandbox: bool) -> None:canvas_id = self._create_canvas()first = self._publish(canvas_id, expected_current_version_id=None)assert first.status_code == status.HTTP_200_OKversion_id = first.json()["current_version_id"]other_user = self._create_user("[email protected]")- self.client.force_login(other_user)+ if sandbox:+ task = Task.objects.create(+ team=self.team,+ channel=self.channel,+ created_by=other_user,+ title="Canvas edit",+ origin_product=Task.OriginProduct.USER_CREATED,+ )+ self.client = self._sandbox_client(task.id, user=other_user)+ self.client.defaults["HTTP_X_POSTHOG_TASK_ID"] = str(task.id)+ else:+ self.client.force_login(other_user)base = f"/api/projects/{self.team.id}/canvases/{canvas_id}"+ rename_payloads: list[tuple[str, dict[str, object]]] = [+ ("publish", {"project": self._project()}),+ ("edit", {"operations": [{"path": "src/canvas.tsx", "content": "export default () => 1"}]}),+ ]+ for action, payload in rename_payloads:+ with self.subTest(action=action):+ rename = self.client.post(+ f"{base}/{action}/",+ {**payload, "name": "Changed", "expected_current_version_id": version_id},+ format="json",+ )+ assert rename.status_code == status.HTTP_403_FORBIDDEN, rename.json()+ canvas = Canvas.objects.unscoped().get(id=canvas_id)+ assert canvas.name == "My canvas"+ assert str(canvas.current_source_version_id) == version_id+ assert CanvasSourceVersion.objects.for_team(self.team.id).filter(canvas_id=canvas_id).count() == 1+metadata_edit = self.client.patch(f"{base}/", {"name": "Changed"}, format="json")source_edit = self.client.post(f"{base}/edit/",@@ -710,26 +786,31 @@ class TestCanvasSourceAndPublish(CanvasAPIBaseTest):},format="json",)+ assert metadata_edit.status_code == status.HTTP_403_FORBIDDEN+ assert source_edit.status_code == status.HTTP_200_OK, source_edit.json()+ edited_version_id = source_edit.json()["current_version_id"]+ assert edited_version_id != version_id+source_publish = self.client.post(f"{base}/publish/",{- "project": self._project("export default function C() { return 2 }"),- "expected_current_version_id": version_id,+ "project": self._project("export default function C() { return 3 }"),+ "expected_current_version_id": edited_version_id,},format="json",)+ assert source_publish.status_code == status.HTTP_200_OK, source_publish.json()+ published_version_id = source_publish.json()["current_version_id"]current_version_publish = self.client.post(f"{base}/publish-current-version/",- {"expected_current_version_id": version_id},+ {"expected_current_version_id": published_version_id},format="json",)- assert metadata_edit.status_code == status.HTTP_404_NOT_FOUND- assert source_edit.status_code == status.HTTP_404_NOT_FOUND- assert source_publish.status_code == status.HTTP_404_NOT_FOUNDassert current_version_publish.status_code == status.HTTP_200_OK, current_version_publish.json()- assert current_version_publish.json()["source_version_id"] == version_id- assert str(Canvas.objects.unscoped().get(id=canvas_id).current_source_version_id) == version_id+ assert current_version_publish.json()["source_version_id"] == published_version_id+ assert str(Canvas.objects.unscoped().get(id=canvas_id).current_source_version_id) == published_version_id+ assert Canvas.objects.unscoped().get(id=canvas_id).name == "My canvas"def test_stale_guard_conflicts(self):canvas_id = self._create_canvas()@@ -1577,7 +1658,8 @@ class TestCanvasErrorReports(CanvasAPIBaseTest):run = TaskRun.objects.filter(task=task).get()prompt = run.state["pending_user_message"]assert canvas_id in prompt- assert "canvas-draft-create" in prompt+ assert "canvas-edit-create" in prompt+ assert "Stage a draft instead only if" in promptassert dispatch.call_count == 1assert dispatch.call_args.kwargs["run_id"] == str(run.id)assert dispatch.call_args.kwargs["skip_user_check"] is True@@ -1596,7 +1678,8 @@ class TestCanvasErrorReports(CanvasAPIBaseTest):assert response.json() == {"request_outcome": "new_run", "task_id": str(task.id)}agent_prompt = TaskRun.objects.get(task=task).state["pending_user_message"]assert prompt in agent_prompt- assert "canvas-draft-create" in agent_prompt+ assert "canvas-edit-create" in agent_prompt+ assert "Stage a draft instead only if" in agent_promptupdate = TaskThreadMessage.objects.for_team(self.team.id).get(content="Run requested from the canvas")assert update.author_id == self.user.iddiff --git a/products/canvas/mcp/tools.yaml b/products/canvas/mcp/tools.yamlindex 3307c9f7ef62..7593f692dfb8 100644--- a/products/canvas/mcp/tools.yaml+++ b/products/canvas/mcp/tools.yaml@@ -72,16 +72,16 @@ tools:description: >Build the COMPLETE source project of a canvas as a DRAFT, without changing the live canvas. The project isvalidated 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`. A project that shows PostHog data must make every figure verifiable- before staging: an insight-backed metric links its saved insight (ph.openExternal with a URL from- generate-app-url); an ad-hoc ph.query figure exposes the exact query that ran in a modal or collapsed area.+ viewers keep seeing the current version. Use it only when the user asked for a draft, a preview, or a review+ step before going live; saving a change with canvas-publish-create or canvas-edit-create is the default.+ 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`. A project that shows PostHog+ data must make every figure verifiable before staging: an insight-backed metric links its saved insight+ (ph.openExternal with a URL from generate-app-url); an ad-hoc ph.query figure exposes the exact query that+ ran in a modal or collapsed area.param_overrides:id:description: ID of the canvas to stage a draft for.@@ -119,8 +119,8 @@ tools:`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. 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.+ like a publish, which is the default way to save a change; stage the complete project as a draft with+ canvas-draft-create only when the user asked for a draft or a review step.param_overrides:id:description: ID of the canvas whose source to edit.@@ -274,9 +274,9 @@ tools:title: Publish canvas source projectdescription: >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+ Publishing goes live immediately and is the default way to save a change, first version or follow-up alike;+ stage the change with canvas-draft-create only when the user asked for a draft or a review step. 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 409version_conflict instead of overwritten; on conflict, re-read the source, re-apply your edits, and publishagainst the new head. A 429 means the team's build capacity is exhausted — wait a moment and retry. Declarediff --git a/products/canvas/skills/building-canvases/SKILL.md b/products/canvas/skills/building-canvases/SKILL.mdindex c988d769220b..f6f59de804fb 100644--- a/products/canvas/skills/building-canvases/SKILL.md+++ b/products/canvas/skills/building-canvases/SKILL.md@@ -119,20 +119,22 @@ matching shape above. The pattern is a hint; the user's actual request remains aruntime and validation rejects undeclared calls.3. Follow `validating-and-publishing-canvases`: validate with `canvas-validate-create` as often asneeded and fix every error-severity diagnostic.-4. Save the project — which tool depends on whether the canvas is already live:+4. Save the project by publishing it — publishing is the default and goes live at once:- **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.+ - **Already live** (`current_version_id` is set): publish per-file changes with+ `canvas-edit-create`, or the complete project with `canvas-publish-create`, passing the+ live `current_version_id` as `expected_current_version_id`.+ - Stage a draft with `canvas-draft-create` only when the user asked for a draft, a preview, or+ a review step before going 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 save again — do not finish thetask with a failed build.-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+Save once per requested change, when the canvas is ready — not after every micro-edit. When the+user asked for a draft, end your reply by saying a draft is ready to preview and promote; the`validating-and-publishing-canvases` skill covers the draft → build → preview → promote flow.End your reply by naming the channel the canvas is in and linking it with the `url` field the@@ -158,9 +160,9 @@ That field is the only valid link to a canvas — never construct one yourself;- **`ph.agent.request(prompt)`** — ask the canvas's authoring agent for a change, with the viewer'sapproval. Declare `agentRequests: true` in `capabilities.posthog`. Call it only from a directclick or form submission — the host shows the exact prompt and asks the viewer to accept before- spending compute, and rejects calls made during render, mount, or polling. The agent stages the- change as a draft for the canvas creator to review; a non-creator's request is filed in the- authoring task's thread instead of starting a run.+ spending compute, and rejects calls made during render, mount, or polling. The agent publishes+ the change as a new version; a non-creator's request is filed in the authoring task's thread+ instead of starting a run.## Source-project shapediff --git a/products/canvas/skills/validating-and-publishing-canvases/SKILL.md b/products/canvas/skills/validating-and-publishing-canvases/SKILL.mdindex e6fa4382b8b9..aa832f73b3de 100644--- a/products/canvas/skills/validating-and-publishing-canvases/SKILL.md+++ b/products/canvas/skills/validating-and-publishing-canvases/SKILL.md@@ -77,9 +77,10 @@ Diagnostics carry `severity`, a stable `code`, a `message`, and (for file-specif## Publish 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.+Publishing goes live immediately and is the default way to save a change, for a canvas's first+version and for every follow-up edit. Every version records who published it and which task did+the work, so the history stays reviewable after the fact. Stage a draft instead only when the user+asked for a draft, a preview, or a review step — see "Draft, then promote" below.Two ways to publish, both guarded:@@ -124,12 +125,11 @@ or its capability declaration.## 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+Publishing goes live the moment its build is ready, and that is the default. Use a draft only+when the user asked for one: a preview to look at first, a review step before going live, or an+explicit "don't publish yet". 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 orpreview.1. **Stage** — `canvas-draft-create` with the complete `project` (same shape, capabilities, and@@ -145,9 +145,9 @@ preview.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+4. **Promote** — when the user approved the draft or asked to go live; a draft the user asked to+ review stays staged until they say so. `canvas-promote-create` makes the draft the live head.+ Pass`expected_current_version_id` (the live `current_version_id` from `canvas-source-retrieve`); itis guarded exactly like a publish and 409s on a moved head (recover as below). A draft whosebuild is still `ready` goes live with no rebuild; otherwise a fresh build is queued, so wait fordiff --git a/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSidePanel.test.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSidePanel.test.tsxindex f0516627ca0e..5cac7a134327 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSidePanel.test.tsx+++ b/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSidePanel.test.tsx@@ -27,7 +27,7 @@ vi.mock("@posthog/ui/features/sessions/components/EmbeddedSessionView", () => ({EmbeddedSessionView: () => <div data-testid="task-chat" />,}));vi.mock("@posthog/ui/features/canvas/freeform/FreeformGenerateBar", () => ({- FreeformGenerateBar: () => null,+ FreeformGenerateBar: () => <div data-testid="canvas-composer" />,}));vi.mock("@posthog/ui/features/canvas/freeform/ContextEditor", () => ({CanvasContextEditor: () => null,@@ -41,7 +41,7 @@ describe("CanvasSidePanel", () => {it("switches from canvas chat to comments for this canvas", () => {render(<CanvasSidePanel- effectiveTaskId="task-1"+ chatTaskId="task-1"commentTaskId="task-1"onMinimize={vi.fn()}dashboardId="canvas-1"@@ -61,25 +61,33 @@ describe("CanvasSidePanel", () => {);});- it("shows the run that built the canvas on the chat tab while viewing", () => {+ it.each([true, false])("ends a run with interactive=%s", (interactive) => {useCanvasChatPanelStore.setState({ tab: "comments", collapsed: false });- render(- <CanvasSidePanel- effectiveTaskId={null}- commentTaskId="task-1"- interactive={false}- onMinimize={vi.fn()}- dashboardId="canvas-1"- channelId="channel-1"- channelName="General"- name="Launch canvas"- displayedVersionId="version-2"- commentVersionLabel={(versionId) => versionId}- onCommentOpen={vi.fn()}- />,+ const props = {+ commentTaskId: "task-1",+ interactive,+ onMinimize: vi.fn(),+ dashboardId: "canvas-1",+ channelId: "channel-1",+ channelName: "General",+ name: "Launch canvas",+ displayedVersionId: "version-2",+ commentVersionLabel: (versionId: string) => versionId,+ onCommentOpen: vi.fn(),+ };+ const { rerender } = render(+ <CanvasSidePanel {...props} chatTaskId="task-1" />,);fireEvent.click(screen.getByText("Chat"));expect(screen.getByTestId("task-chat")).toBeInTheDocument();++ rerender(<CanvasSidePanel {...props} chatTaskId={null} />);+ expect(screen.queryByTestId("task-chat")).not.toBeInTheDocument();+ if (interactive) {+ expect(screen.getByTestId("canvas-composer")).toBeInTheDocument();+ } else {+ expect(screen.getByText("No active run")).toBeInTheDocument();+ }});});diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSidePanel.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSidePanel.tsxindex f02265793500..67fab146637d 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSidePanel.tsx+++ b/products/desktop/packages/ui/src/features/canvas/freeform/CanvasSidePanel.tsx@@ -1,6 +1,15 @@-import { SidebarSimpleIcon, SpinnerGapIcon } from "@phosphor-icons/react";+import {+ ChatCircleIcon,+ SidebarSimpleIcon,+ SpinnerGapIcon,+} from "@phosphor-icons/react";import {Button,+ Empty,+ EmptyDescription,+ EmptyHeader,+ EmptyMedia,+ EmptyTitle,Tabs,TabsList,TabsTrigger,@@ -24,10 +33,11 @@ import { type Ref, useEffect, useRef } from "react";// The canvas's right-hand dock. While a generation/edit run is in flight it// shows that run's live chat (steering/queue included); otherwise it shows the-// edit composer for the next change. Header carries a minimize control that-// collapses the panel to a thin rail (handled by the parent).+// edit composer, which starts a new run (and so a new session) for the next+// change. Header carries a minimize control that collapses the panel to a thin+// rail (handled by the parent).export function CanvasSidePanel({- effectiveTaskId,+ chatTaskId,commentTaskId,interactive,onMinimize,@@ -43,10 +53,14 @@ export function CanvasSidePanel({editorRef,onStarted,}: {- effectiveTaskId: string | null;+ /** The run whose live chat the panel shows: the one in flight right now, or+ * null once it finished. A finished run's chat is not shown again, so every+ * visit starts from the composer instead of the session that built the+ * canvas. */+ chatTaskId: string | null;commentTaskId: string | null;/** Whether the canvas is being edited. The composer is an edit affordance, so- * view mode falls back to the conversation that last built the canvas. */+ * view mode shows an empty chat when no run is in flight. */interactive?: boolean;onMinimize: () => void;dashboardId: string;@@ -66,17 +80,14 @@ export function CanvasSidePanel({}) {const tab = useCanvasChatPanelStore((state) => state.tab);const setTab = useCanvasChatPanelStore((state) => state.setTab);- const previousTaskId = useRef(effectiveTaskId);- // With no run in flight, edit mode gets the composer for the next change,- // while view mode gets the chat of the run that produced this canvas.- const chatTaskId = effectiveTaskId ?? (interactive ? null : commentTaskId);+ const previousTaskId = useRef(chatTaskId);useEffect(() => {- if (effectiveTaskId && effectiveTaskId !== previousTaskId.current) {+ if (chatTaskId && chatTaskId !== previousTaskId.current) {setTab("chat");}- previousTaskId.current = effectiveTaskId;- }, [effectiveTaskId, setTab]);+ previousTaskId.current = chatTaskId;+ }, [chatTaskId, setTab]);return (<div className="flex h-full min-w-0 flex-col bg-gray-1">@@ -127,6 +138,19 @@ export function CanvasSidePanel({/>) : chatTaskId ? (<CanvasChatLoader taskId={chatTaskId} />+ ) : !interactive ? (+ <Empty className="h-full border-0">+ <EmptyHeader>+ <EmptyMedia variant="icon">+ <ChatCircleIcon size={24} />+ </EmptyMedia>+ <EmptyTitle>No active run</EmptyTitle>+ <EmptyDescription>+ Select Edit to start a new agent run on this canvas. Each run+ publishes a new version.+ </EmptyDescription>+ </EmptyHeader>+ </Empty>) : (<div className="flex h-full min-h-0 flex-col gap-3 p-3"><FreeformGenerateBardiff --git a/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsxindex dae4c63adcf1..27d0ba3aefc9 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsx+++ b/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsx@@ -16,7 +16,10 @@ import {latestFinishedCanvasBuild,publishedCanvasBuild,} from "@posthog/core/canvas/canvasBuildSchemas";-import type { CanvasDraft } from "@posthog/core/canvas/dashboardSchemas";+import type {+ CanvasDraft,+ CanvasVersion,+} from "@posthog/core/canvas/dashboardSchemas";import {type CanvasAgentRequestResult,type CanvasAnalyticsConfig,@@ -40,12 +43,16 @@ import {EmptyHeader,EmptyMedia,EmptyTitle,+ ItemContent,+ ItemDescription,+ ItemMenuItem,+ ItemTitle,Tooltip as QuillTooltip,TooltipContent,TooltipProvider,TooltipTrigger,} from "@posthog/quill";-import { CANVAS_COMPONENT_PATH } from "@posthog/shared";+import { CANVAS_COMPONENT_PATH, formatRelativeAge } from "@posthog/shared";import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";import {isCanvasGenerating,@@ -133,8 +140,13 @@ const AGENT_REQUEST_OUTCOME_TOASTS: Record<reported: "Request sent to the canvas creator",};-// 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 describeCanvasVersion(version: CanvasVersion): string {+ const age = formatRelativeAge(version.createdAt);+ return version.createdBy+ ? `Published by ${version.createdBy} · ${age}`+ : `Published ${age}`;+}+function draftBadgeVariant(status: CanvasDraft["buildStatus"],): "default" | "warning" | "success" | "destructive" {@@ -197,12 +209,10 @@ export function FreeformCanvasView({const channelId = dashboard?.channelId ?? "";useEffect(() => {- if (genTaskId) setStartedTaskId(null);- }, [genTaskId]);+ if (genTaskId === startedTaskId) setStartedTaskId(null);+ }, [genTaskId, startedTaskId]);- // The run whose chat the panel shows: the record's id, or the optimistic- // bridge until the poll catches up.- const effectiveTaskId = genTaskId ?? startedTaskId;+ const effectiveTaskId = startedTaskId ?? genTaskId;const { channels } = useChannels();const channelName = useMemo(@@ -234,13 +244,18 @@ export function FreeformCanvasView({// Whether the agent is actively producing the canvas right now. Drives the// "Generating…" UI (notice, composer, undo/redo). Shares the tested helper// with the completion-toast watcher so both read the same signal. Keys off- // effectiveTaskId (genTaskId ?? startedTaskId), matching isSyncing above.+ // effectiveTaskId, matching isSyncing above.const isGenerating = isCanvasGenerating({genTaskId: effectiveTaskId,genTaskLoading,latestRun: genTask?.latest_run,session: genSession,});+ // The run whose live chat the panel shows: only one that is still in flight.+ // The record keeps a finished run's id (comments hang off it), but its chat+ // is not reopened, so every visit starts a fresh run from the composer.+ const chatTaskId =+ startedTaskId ?? (isGenerating && !genTaskLoading ? genTaskId : null);// Poll the record while the session is alive so a just-published head version// appears (the publish lands while the prompt is still pending).@@ -325,6 +340,8 @@ export function FreeformCanvasView({const browsingDraft = drafts.some((draft) => draft.versionId === browseVersionId,);+ const browsedVersion =+ versions.find((version) => version.id === browseVersionId) ?? null;// 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@@ -716,23 +733,23 @@ export function FreeformCanvasView({const editorRef = useRef<EditorHandle>(null);const setPanelTab = useCanvasChatPanelStore((s) => s.setTab);const draftActions = useDraftStore((s) => s.actions);- // Reveal the panel's chat composer and prefill it. A canvas that has ever- // generated shows the task session's composer, which receives content- // through the draft store keyed by task id — the editor ref only exists on- // the generate bar a never-generated canvas mounts.+ // Reveal the panel's chat composer and prefill it. While a run is in flight+ // the panel shows that session's composer, which receives content through+ // the draft store keyed by task id — otherwise the generate bar's editor ref+ // is the composer.const prefillComposer = useCallback((message: string) => {setCollapsed(false);setPanelTab("chat");- if (effectiveTaskId) {- draftActions.setPendingContent(effectiveTaskId, textToContent(message));- draftActions.requestFocus(effectiveTaskId);+ if (chatTaskId) {+ draftActions.setPendingContent(chatTaskId, textToContent(message));+ draftActions.requestFocus(chatTaskId);return;}editorRef.current?.setContent(message);editorRef.current?.focus();},- [setCollapsed, setPanelTab, effectiveTaskId, draftActions],+ [setCollapsed, setPanelTab, chatTaskId, draftActions],);const askAgentToFix = () => {if (!runtimeError) return;@@ -755,7 +772,7 @@ export function FreeformCanvasView({const showHero =interactive &&!hasContent &&- !effectiveTaskId &&+ !chatTaskId &&!dashboardLoading &&!buildsLoading &&!headSourceLoading;@@ -782,7 +799,7 @@ export function FreeformCanvasView({const panelVisibility = canvasSidePanelVisibility({interactive,hasContent,- hasActiveTask: !!effectiveTaskId,+ hasActiveTask: !!chatTaskId,generatingPanelOpen,viewOpen: embedded ? false : panelViewOpen,collapsed,@@ -854,10 +871,50 @@ export function FreeformCanvasView({</Badge>) : (versions.length > 0 && (- <Text size="1" className="ml-1 text-gray-9">- v{versions.length - currentIndex}/{versions.length}- {!browsing && " · Live"}- </Text>+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ size="sm"+ variant="default"+ className="ml-1"+ aria-label="Version history"+ />+ }+ >+ v{versions.length - currentIndex}/{versions.length}+ {!browsing && " · Live"}+ <CaretDownIcon size={12} />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" side="bottom">+ {versions.map((version, index) => (+ <DropdownMenuItem+ key={version.id}+ render={+ <ItemMenuItem size="xs" className="w-full" />+ }+ onClick={() =>+ setBrowseVersion(+ threadId,+ version.id === headVersionId+ ? null+ : version.id,+ )+ }+ >+ <ItemContent variant="menuItem">+ <ItemTitle>+ v{versions.length - index}+ {version.id === headVersionId && " · Live"}+ </ItemTitle>+ <ItemDescription className="leading-none">+ {describeCanvasVersion(version)}+ </ItemDescription>+ </ItemContent>+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>))}{browsing && !browsingDraft && (@@ -974,9 +1031,7 @@ export function FreeformCanvasView({showPanel &&collapsed &&!generatingPanelOpen && (- <Tooltip- content={effectiveTaskId ? "Show chat" : "Edit canvas"}- >+ <Tooltip content={chatTaskId ? "Show chat" : "Edit canvas"}><Buttonsize="icon"variant="default"@@ -1018,10 +1073,28 @@ export function FreeformCanvasView({<Text size="1">{browsingDraft? "Viewing a draft. It isn't live yet."- : "Viewing a previous version"}+ : browsedVersion+ ? `Viewing a previous version. ${describeCanvasVersion(browsedVersion)}`+ : "Viewing a previous version"}</Text></Flex><Flex align="center" gap="2">+ {browsedVersion?.taskId && (+ <Button+ variant="link-muted"+ size="sm"+ render={+ <Link+ to="/tasks/$taskId"+ params={{+ taskId: browsedVersion.taskId,+ }}+ />+ }+ >+ View task+ </Button>+ )}<Buttonvariant="outline"size="sm"@@ -1217,7 +1290,7 @@ export function FreeformCanvasView({overflow:hidden) so the embedded run's session — and its activityheartbeat — stays alive and chat scroll survives a minimize. */}<CanvasSidePanel- effectiveTaskId={effectiveTaskId}+ chatTaskId={chatTaskId}commentTaskId={commentTaskId}interactive={interactive}onMinimize={() => {diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 34c362d94f79..c7f123dc8567 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -1115,7 +1115,7 @@}},"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`. A project that shows PostHog data must make every figure verifiable before staging: an insight-backed metric links its saved insight (ph.openExternal with a URL from generate-app-url); an ad-hoc ph.query figure exposes the exact query that ran in a modal or collapsed area.",+ "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. Use it only when the user asked for a draft, a preview, or a review step before going live; saving a change with canvas-publish-create or canvas-edit-create is the default. 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`. A project that shows PostHog data must make every figure verifiable before staging: an insight-backed metric links its saved insight (ph.openExternal with a URL from generate-app-url); an ad-hoc ph.query figure exposes the exact query that ran in a modal or collapsed area.","category": "Canvas","feature": "canvas","summary": "Stage a canvas draft build",@@ -1143,7 +1143,7 @@}},"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. 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.",+ "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, which is the default way to save a change; stage the complete project as a draft with canvas-draft-create only when the user asked for a draft or a review step.","category": "Canvas","feature": "canvas","summary": "Edit canvas source files",@@ -1241,7 +1241,7 @@}},"canvas-publish-create": {- "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`. A project that shows PostHog data must make every figure verifiable before publishing: an insight-backed metric links its saved insight (ph.openExternal with a URL from generate-app-url); an ad-hoc ph.query figure exposes the exact query that ran in a modal or collapsed area. 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 and is the default way to save a change, first version or follow-up alike; stage the change with canvas-draft-create only when the user asked for a draft or a review step. 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`. A project that shows PostHog data must make every figure verifiable before publishing: an insight-backed metric links its saved insight (ph.openExternal with a URL from generate-app-url); an ad-hoc ph.query figure exposes the exact query that ran in a modal or collapsed area. 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 94fb5fb6e2b2..a2490298a02f 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -1130,7 +1130,7 @@}},"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`. A project that shows PostHog data must make every figure verifiable before staging: an insight-backed metric links its saved insight (ph.openExternal with a URL from generate-app-url); an ad-hoc ph.query figure exposes the exact query that ran in a modal or collapsed area.",+ "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. Use it only when the user asked for a draft, a preview, or a review step before going live; saving a change with canvas-publish-create or canvas-edit-create is the default. 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`. A project that shows PostHog data must make every figure verifiable before staging: an insight-backed metric links its saved insight (ph.openExternal with a URL from generate-app-url); an ad-hoc ph.query figure exposes the exact query that ran in a modal or collapsed area.","category": "Canvas","feature": "canvas","summary": "Stage a canvas draft build",@@ -1158,7 +1158,7 @@}},"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. 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.",+ "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, which is the default way to save a change; stage the complete project as a draft with canvas-draft-create only when the user asked for a draft or a review step.","category": "Canvas","feature": "canvas","summary": "Edit canvas source files",@@ -1256,7 +1256,7 @@}},"canvas-publish-create": {- "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`. A project that shows PostHog data must make every figure verifiable before publishing: an insight-backed metric links its saved insight (ph.openExternal with a URL from generate-app-url); an ad-hoc ph.query figure exposes the exact query that ran in a modal or collapsed area. 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 and is the default way to save a change, first version or follow-up alike; stage the change with canvas-draft-create only when the user asked for a draft or a review step. 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`. A project that shows PostHog data must make every figure verifiable before publishing: an insight-backed metric links its saved insight (ph.openExternal with a URL from generate-app-url); an ad-hoc ph.query figure exposes the exact query that ran in a modal or collapsed area. The canvas lives in PostHog, not on disk — this tool is what saves it.","category": "Canvas","feature": "canvas","summary": "Publish canvas source project",