: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): make agent canvas edits faster and safer (#105420)
Shy Alter5617caf2eba9
diff --git a/products/canvas/backend/build_service.py b/products/canvas/backend/build_service.pyindex 5124d0f307c6..de0fd786982e 100644--- a/products/canvas/backend/build_service.py+++ b/products/canvas/backend/build_service.py@@ -19,6 +19,7 @@ exists elsewhere).import gzipimport json+import timeimport shutilimport hashlibimport subprocess@@ -70,6 +71,8 @@ logger = structlog.get_logger(__name__)MAX_ACTIVE_CANVAS_BUILDS_PER_TEAM = 20MAX_PINNED_BUILDS_PER_CANVAS = 10MAX_BUILD_ATTEMPTS = 3+PUBLISH_BUILD_WAIT_SECONDS = 3.0+_PUBLISH_BUILD_POLL_SECONDS = 0.2@frozen@@ -674,6 +677,15 @@ def commit_source_project_draft(return version, build+def wait_for_build_result(build: CanvasBuild) -> CanvasBuild:+ deadline = time.monotonic() + PUBLISH_BUILD_WAIT_SECONDS+ while True:+ build = CanvasBuild.objects.unscoped().get(id=build.id)+ if build.status not in CanvasBuild.ACTIVE_STATUSES or time.monotonic() >= deadline:+ return build+ time.sleep(_PUBLISH_BUILD_POLL_SECONDS)++def publish_source_project(canvas: Canvas,*,@@ -1214,6 +1226,7 @@ def _capture_build_completed(build: CanvasBuild, *, outcome: str) -> None:event="canvas build completed",properties={"canvas_id": str(build.canvas_id),+ "canvas_kind": build.canvas.kind,"build_id": str(build.id),"source_version_id": str(build.source_version_id),"outcome": outcome,diff --git a/products/canvas/backend/facade/api.py b/products/canvas/backend/facade/api.pyindex f1f817747148..b58e402b0eb8 100644--- a/products/canvas/backend/facade/api.py+++ b/products/canvas/backend/facade/api.py@@ -18,6 +18,7 @@ from products.canvas.backend.layout import (validate_layout as validate_layout,validate_layout_references as validate_layout_references,)+from products.canvas.backend.source_edits import apply_source_edits as apply_source_editsfrom products.canvas.backend.state_reads import CanvasStateReader as CanvasStateReaderfrom products.canvas.backend.teaching import (RESERVED_TEMPLATE_IDS as RESERVED_TEMPLATE_IDS,diff --git a/products/canvas/backend/presentation/serializers.py b/products/canvas/backend/presentation/serializers.pyindex 9b1f87f05c0f..be5c5ae43d4d 100644--- a/products/canvas/backend/presentation/serializers.py+++ b/products/canvas/backend/presentation/serializers.py@@ -707,19 +707,81 @@ class CanvasSourcePublishSerializer(serializers.Serializer):)+class CanvasSourceEditOp(models.TextChoices):+ WRITE = "write"+ DELETE = "delete"+ RENAME = "rename"+ STR_REPLACE = "str_replace"+++def _inferred_edit_op(attrs: dict[str, Any]) -> CanvasSourceEditOp:+ if "old_string" in attrs or "new_string" in attrs:+ return CanvasSourceEditOp.STR_REPLACE+ if attrs.get("new_path"):+ return CanvasSourceEditOp.RENAME+ if "content" not in attrs:+ raise serializers.ValidationError({"op": "Set op, or send content (null deletes the file)."})+ return CanvasSourceEditOp.WRITE if attrs["content"] is not None else CanvasSourceEditOp.DELETE++class CanvasSourceEditOperationSerializer(serializers.Serializer):- """One per-file edit: set a file's content, or delete it."""+ """One file edit: replace text in a file, write a whole file, delete it, or rename it."""- path = serializers.CharField(- help_text='Project-relative path of the file to write or delete (e.g. "src/canvas.tsx").'+ op = serializers.ChoiceField(+ choices=CanvasSourceEditOp.choices,+ required=False,+ help_text=(+ "What to do. 'str_replace' replaces old_string with new_string inside the file: the default for "+ "changing an existing file. 'write' sets the file's complete content (new files, full rewrites). "+ "'delete' removes the file. 'rename' moves it to new_path. When omitted, it follows the fields sent: "+ "old_string or new_string means 'str_replace', new_path means 'rename', non-null content means 'write', "+ "and content null means 'delete'. An operation with none of these fields is rejected."+ ),)+ path = serializers.CharField(help_text='Project-relative path of the file to edit (e.g. "src/canvas.tsx").')content = serializers.CharField(required=False,allow_null=True,allow_blank=True,trim_whitespace=False,- help_text="The file's complete new content. Null (or omitted) deletes the file.",+ help_text="For 'write': the file's complete new content.",+ )+ old_string = serializers.CharField(+ required=False,+ trim_whitespace=False,+ help_text=(+ "For 'str_replace': the exact text to replace, copied from the file with a few surrounding lines so it "+ "matches one place only. If whitespace differs slightly, a unique line-by-line match is still accepted."+ ),+ )+ new_string = serializers.CharField(+ required=False,+ allow_blank=True,+ trim_whitespace=False,+ help_text="For 'str_replace': the text that replaces old_string. An empty string deletes old_string.",)+ replace_all = serializers.BooleanField(+ required=False,+ default=False,+ help_text="For 'str_replace': replace every exact match of old_string instead of requiring exactly one.",+ )+ new_path = serializers.CharField(required=False, help_text="For 'rename': the file's new project-relative path.")++ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:+ op = attrs.get("op")+ if op is None:+ op = attrs["op"] = _inferred_edit_op(attrs)+ if op == CanvasSourceEditOp.WRITE and attrs.get("content") is None:+ raise serializers.ValidationError({"content": "A 'write' operation needs the file's complete content."})+ elif op == CanvasSourceEditOp.RENAME and not attrs.get("new_path"):+ raise serializers.ValidationError({"new_path": "A 'rename' operation needs new_path."})+ elif op == CanvasSourceEditOp.STR_REPLACE:+ missing = [field for field in ("old_string", "new_string") if field not in attrs]+ if missing:+ raise serializers.ValidationError(+ dict.fromkeys(missing, "A 'str_replace' operation needs old_string and new_string.")+ )+ return attrsclass CanvasSourceEditSerializer(serializers.Serializer):@@ -727,8 +789,21 @@ class CanvasSourceEditSerializer(serializers.Serializer):operations = CanvasSourceEditOperationSerializer(many=True,- allow_empty=False,- help_text="Edits applied in order to the canvas's current source project.",+ required=False,+ default=list,+ help_text=(+ "Edits applied in order to the canvas's current source project, all or nothing. "+ "May be empty when the edit only changes capabilities."+ ),+ )+ capabilities = CanvasCapabilitiesSerializer(+ required=False,+ help_text=(+ "The project's complete new capabilities, replacing the current ones in the same publish. "+ "Send it when the change needs a capability the canvas does not declare yet, for example a new "+ "ph.state scope, insight, capture event, or network origin. Copy the current capabilities from "+ "canvas-source-retrieve and change only what you need. Omit to keep the current capabilities."+ ),)prompt = serializers.CharField(required=False,@@ -752,6 +827,11 @@ class CanvasSourceEditSerializer(serializers.Serializer):),)+ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:+ if not attrs["operations"] and "capabilities" not in attrs:+ raise serializers.ValidationError({"operations": "Send at least one operation or new capabilities."})+ return attrs+class CanvasPublishCurrentVersionSerializer(serializers.Serializer):expected_current_version_id = serializers.UUIDField(@@ -759,6 +839,25 @@ class CanvasPublishCurrentVersionSerializer(serializers.Serializer):)+class CanvasPublishedBuildSerializer(serializers.Serializer):+ """The build a publish queued, as it stood when the response was sent."""++ id = serializers.CharField(help_text="The build's id.")+ build_status = serializers.ChoiceField(+ choices=["queued", "building", "ready", "failed"],+ source="status",+ help_text=(+ "'ready': the build finished. The canvas is live with this version when canvas.published_build_id "+ "equals this id; then you do not need canvas-builds-retrieve. "+ "'failed': fix the error diagnostics and save again. "+ "'queued' or 'building': poll canvas-builds-retrieve until the build is terminal."+ ),+ )+ diagnostics = CanvasDiagnosticSerializer(+ many=True, help_text="Structured diagnostics recorded by the build (errors explain a failed status)."+ )++class CanvasSourcePublishResponseSerializer(serializers.Serializer):"""Result of a successful source-project publish."""@@ -768,6 +867,9 @@ class CanvasSourcePublishResponseSerializer(serializers.Serializer):many=True,help_text="Advisory (warning-severity) diagnostics recorded for the published project.",)+ build = CanvasPublishedBuildSerializer(+ help_text="The queued build. The server waits a few seconds for it, so it is often already terminal."+ )class CanvasPublishConflictSerializer(serializers.Serializer):diff --git a/products/canvas/backend/presentation/views.py b/products/canvas/backend/presentation/views.pyindex 67ca9308dab3..2ed73f5a7d1d 100644--- a/products/canvas/backend/presentation/views.py+++ b/products/canvas/backend/presentation/views.py@@ -1,5 +1,7 @@import jsonimport hashlib+from collections import Counter+from collections.abc import Sequencefrom typing import Any, castfrom uuid import UUID@@ -37,6 +39,7 @@ from products.canvas.backend.contract import contract_limitsfrom products.canvas.backend.facade.api import (CanvasStateReader,apply_layout_ops,+ apply_source_edits,call_connector_tool,canvas_connectors_enabled,connector_listings,@@ -78,6 +81,7 @@ from products.canvas.backend.presentation.serializers import (CanvasSerializer,CanvasSourceDraftResponseSerializer,CanvasSourceDraftSerializer,+ CanvasSourceEditOp,CanvasSourceEditSerializer,CanvasSourceInvalidSerializer,CanvasSourcePublishResponseSerializer,@@ -97,7 +101,7 @@ from products.canvas.backend.presentation.serializers import (CanvasViewResponseSerializer,canvas_url,)-from products.canvas.backend.source import apply_source_edits, has_errors, validate_source_project+from products.canvas.backend.source import has_errors, validate_source_projectfrom products.tasks.backend.facade import api as tasks_facadefrom products.tasks.backend.facade.access import code_access_required_response@@ -122,6 +126,14 @@ def _capacity_response() -> Response:)+def _edit_operation_properties(operations: Sequence[dict[str, Any]]) -> dict[str, int]:+ counts = Counter(operation["op"] for operation in operations)+ return {+ "operation_count": len(operations),+ **{f"{op}_operation_count": counts[op] for op in CanvasSourceEditOp.values},+ }++def _conflict_response(error: build_service.CanvasVersionConflict) -> Response:return Response({@@ -934,7 +946,7 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.ModelViewSet):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.",+ description="An operation did not apply (a missing file, or old_string matched no place or several), or the edited project failed validation.",),409: OpenApiResponse(response=CanvasPublishConflictSerializer,@@ -945,11 +957,11 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.ModelViewSet):)@action(methods=["POST"], detail=True)def edit(self, request: Request, *args: Any, **kwargs: Any) -> Response:- """Publish per-file edits against the canvas's current source project.+ """Publish file edits against the canvas's current source project.- Diff-aware alternative to sending the complete project: each operation- sets a file's content or (content null) deletes it, applied to the head- the caller read. `expected_current_version_id` is mandatory here —+ Diff-aware alternative to sending the complete project: operations+ replace text inside a file, write, delete, or rename files, applied in+ order to the head the caller read. `expected_current_version_id` is mandatory here —relative edits against an unverified base could silently merge intosomeone else's newer work."""@@ -961,14 +973,25 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.ModelViewSet):payload.is_valid(raise_exception=True)try:- project, _ = build_service.current_source_project(canvas)+ project, head_version_id = build_service.current_source_project(canvas)except ObjectStorageError:return Response({"detail": "The canvas's source is temporarily unavailable."},status=status.HTTP_503_SERVICE_UNAVAILABLE,)- project, diagnostics = apply_source_edits(project, payload.validated_data["operations"])+ if (payload.validated_data["expected_current_version_id"] or None) != head_version_id:+ return _conflict_response(build_service.CanvasVersionConflict(head_version_id))+ operations = payload.validated_data["operations"]+ project, diagnostics = apply_source_edits(project, operations)+ if "capabilities" in payload.validated_data:+ project = {**project, "capabilities": payload.validated_data["capabilities"]}if diagnostics:+ self._report_canvas_action(+ "canvas edit rejected",+ canvas,+ error_codes=sorted({entry["code"] for entry in diagnostics}),+ **_edit_operation_properties(operations),+ )return Response({"detail": "The edit could not be applied to the canvas's current source.",@@ -986,6 +1009,7 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.ModelViewSet):name=payload.validated_data.get("name"),has_expected_version=True,expected_version_id=payload.validated_data["expected_current_version_id"],+ edit_operations=operations,)def _publish(@@ -998,6 +1022,7 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.ModelViewSet):name: str | None,has_expected_version: bool,expected_version_id: str | None,+ edit_operations: Sequence[dict[str, Any]] | None = None,) -> Response:user = self._request_user()if name is not None and (user is None or canvas.created_by_id != user.id):@@ -1009,7 +1034,7 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.ModelViewSet):task_id = self._sandbox_task_id(request)try:- canvas, version, _build, first_publish = build_service.publish_source_project(+ canvas, version, build, first_publish = build_service.publish_source_project(canvas,project=project,prompt=prompt,@@ -1046,14 +1071,16 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.ModelViewSet):inline_queries_capability=bool(posthog_capabilities.get("inlineQueries")),agent_requests_capability=bool(posthog_capabilities.get("agentRequests")),is_sandbox_publish=task_id is not None,+ save_method="publish" if edit_operations is None else "edit",+ **(_edit_operation_properties(edit_operations) if edit_operations is not None else {}),)+ build = build_service.wait_for_build_result(build)+ canvas.refresh_from_db()return Response(- {- "canvas": CanvasSummarySerializer(canvas).data,- "current_version_id": str(version.id),- "diagnostics": diagnostics,- }+ CanvasSourcePublishResponseSerializer(+ {"canvas": canvas, "current_version_id": str(version.id), "diagnostics": diagnostics, "build": build}+ ).data)@extend_schema(@@ -2278,7 +2305,12 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.ModelViewSet):report_user_action(user,event,- {"canvas_id": str(canvas.id), "channel_id": str(canvas.channel_id), **extra},+ {+ "canvas_id": str(canvas.id),+ "channel_id": str(canvas.channel_id),+ "canvas_kind": canvas.kind,+ **extra,+ },team=self.team,request=self.request,)diff --git a/products/canvas/backend/source.py b/products/canvas/backend/source.pyindex 351f2b7ebd3a..7aa68790b0d0 100644--- a/products/canvas/backend/source.py+++ b/products/canvas/backend/source.py@@ -221,36 +221,6 @@ def synthetic_source_project(legacy_code: str | None) -> dict[str, Any]:}-def apply_source_edits(- project: dict[str, Any], operations: list[dict[str, Any]]-) -> tuple[dict[str, Any], list[dict[str, Any]]]:- """Apply per-file set/delete operations to a source project.-- Returns the edited project (input untouched) and diagnostics; any- diagnostic means the edit set could not be applied atomically.- """- project = {**project, "files": dict(project["files"])}- diagnostics: list[dict[str, Any]] = []- for operation in operations:- path = operation["path"]- content = operation.get("content")- if content is None:- if path not in project["files"]:- diagnostics.append(- diagnostic(- "error",- "edit_target_missing",- f"cannot delete {path} — the project has no file at that path",- path=path,- )- )- continue- del project["files"][path]- else:- project["files"][path] = content- return project, diagnostics--def validate_relative_path(path: str, *, restrict_charset: bool = True) -> str | None:"""Validate a relative, forward-slash file path; returns the problem or None.diff --git a/products/canvas/backend/source_edits.py b/products/canvas/backend/source_edits.pynew file mode 100644index 000000000000..b6d4d2cd2f65--- /dev/null+++ b/products/canvas/backend/source_edits.py@@ -0,0 +1,178 @@+import difflib+from collections.abc import Callable+from typing import Any++from posthog.dataclasses import frozen++from products.canvas.backend.contract import contract_limits+from products.canvas.backend.source import diagnostic++_NO_MATCH_EXCERPT_LINES = 5+_MAX_COMPARED_LINE_CHARS = 200+_REPORTED_MATCH_LINES = 5+_LINE_SEPARATOR = "\x00"+++@frozen+class EditProblem:+ code: str+ message: str+ line: int | None+++def apply_source_edits(+ project: dict[str, Any], operations: list[dict[str, Any]]+) -> tuple[dict[str, Any], list[dict[str, Any]]]:+ files = dict(project["files"])+ diagnostics: list[dict[str, Any]] = []+ for index, operation in enumerate(operations):+ problem = _apply_source_edit(files, operation, index)+ if problem is not None:+ diagnostics.append(problem)+ return {**project, "files": files}, diagnostics+++def _apply_source_edit(files: dict[str, str], operation: dict[str, Any], index: int) -> dict[str, Any] | None:+ kind = operation["op"]+ path = operation["path"]+ if kind == "write":+ files[path] = operation["content"]+ return None+ if path not in files:+ return diagnostic(+ "error", "edit_target_missing", f"operation {index}: the project has no file at {path}", path=path+ )+ if kind == "delete":+ del files[path]+ return None+ if kind == "rename":+ new_path = operation["new_path"]+ if new_path in files:+ return diagnostic(+ "error",+ "edit_target_exists",+ f"operation {index}: cannot rename {path} to {new_path} because a file already exists there",+ path=path,+ )+ files[new_path] = files.pop(path)+ return None+ result = _replace_in_file(+ files[path], operation["old_string"], operation["new_string"], replace_all=operation.get("replace_all", False)+ )+ if isinstance(result, EditProblem):+ return diagnostic("error", result.code, f"operation {index}: {result.message}", path=path, line=result.line)+ files[path] = result+ return None+++def _replace_in_file(text: str, old: str, new: str, *, replace_all: bool) -> str | EditProblem:+ count = text.count(old)+ if count == 1 or (count > 1 and replace_all):+ max_chars = contract_limits()["maxSourceFileBytes"]+ if len(text) + count * (len(new) - len(old)) > max_chars:+ return EditProblem(+ code="edit_too_large",+ message=f"the edited file would exceed the {max_chars // 1024} KB per-file limit.",+ line=None,+ )+ return text.replace(old, new)+ if count > 1:+ lines = _exact_match_lines(text, old)+ return EditProblem(+ code="edit_ambiguous_match",+ message=f"old_string matches {count} places (lines {', '.join(map(str, lines))}). "+ "Include more surrounding lines to make it unique, or set replace_all to replace every match.",+ line=lines[0],+ )+ if not replace_all and _LINE_SEPARATOR not in text and _LINE_SEPARATOR not in old:+ eol = "\r\n" if "\r\n" in text else "\n"+ file_lines = text.split(eol)+ old_lines = _edit_lines(old)+ if any(line.strip() for line in old_lines):+ for normalize in (str.rstrip, str.strip):+ starts = _loose_match_starts(file_lines, old_lines, normalize)+ if len(starts) == 1:+ start = starts[0]+ matched = file_lines[start : start + len(old_lines)]+ file_lines[start : start + len(old_lines)] = _reindent(_edit_lines(new), old_lines, matched)+ return eol.join(file_lines)+ if len(starts) > 1:+ return EditProblem(+ code="edit_ambiguous_match",+ message="old_string matches more than one place when whitespace is ignored "+ f"(lines {', '.join(str(start + 1) for start in starts)}). "+ "Include more surrounding lines to make it unique.",+ line=starts[0] + 1,+ )+ return _no_match_problem(text, old)+++def _edit_lines(value: str) -> list[str]:+ lines = value.replace("\r\n", "\n").split("\n")+ if len(lines) > 1 and lines[-1] == "":+ lines.pop()+ return lines+++def _exact_match_lines(text: str, old: str) -> list[int]:+ lines: list[int] = []+ line, scanned = 1, 0+ position = text.find(old)+ while position != -1 and len(lines) < _REPORTED_MATCH_LINES:+ line += text.count("\n", scanned, position)+ scanned = position+ lines.append(line)+ position = text.find(old, position + len(old))+ return lines+++def _loose_match_starts(file_lines: list[str], old_lines: list[str], normalize: Callable[[str], str]) -> list[int]:+ haystack = _LINE_SEPARATOR + _LINE_SEPARATOR.join(map(normalize, file_lines)) + _LINE_SEPARATOR+ needle = _LINE_SEPARATOR + _LINE_SEPARATOR.join(map(normalize, old_lines)) + _LINE_SEPARATOR+ starts: list[int] = []+ position = haystack.find(needle)+ while position != -1 and len(starts) < _REPORTED_MATCH_LINES:+ starts.append(haystack.count(_LINE_SEPARATOR, 0, position))+ position = haystack.find(needle, position + 1)+ return starts+++def _reindent(new_lines: list[str], old_lines: list[str], matched_lines: list[str]) -> list[str]:+ old_indent = _indent_of(next((line for line in old_lines if line.strip()), ""))+ file_indent = _indent_of(next((line for line in matched_lines if line.strip()), ""))+ if file_indent.startswith(old_indent):+ extra = file_indent[len(old_indent) :]+ return [extra + line if line.strip() else line for line in new_lines]+ if old_indent.startswith(file_indent):+ surplus = old_indent[len(file_indent) :]+ return [line[len(surplus) :] if line.startswith(surplus) else line for line in new_lines]+ return new_lines+++def _indent_of(line: str) -> str:+ return line[: len(line) - len(line.lstrip())]+++def _no_match_problem(text: str, old: str) -> EditProblem:+ anchor = next((line.strip() for line in old.splitlines() if line.strip()), "")+ file_lines = text.splitlines()+ if not anchor or not file_lines:+ return EditProblem(code="edit_no_match", message="old_string was not found in the file.", line=None)+ matcher = difflib.SequenceMatcher(None, anchor[:_MAX_COMPARED_LINE_CHARS], "")+ best, best_ratio = 0, -1.0+ for index, line in enumerate(file_lines):+ matcher.set_seq2(line.strip()[:_MAX_COMPARED_LINE_CHARS])+ if matcher.real_quick_ratio() <= best_ratio or matcher.quick_ratio() <= best_ratio:+ continue+ ratio = matcher.ratio()+ if ratio > best_ratio:+ best, best_ratio = index, ratio+ excerpt = "\n".join(+ f"{number + 1}: {file_lines[number][:_MAX_COMPARED_LINE_CHARS]}"+ for number in range(best, min(best + _NO_MATCH_EXCERPT_LINES, len(file_lines)))+ )+ return EditProblem(+ code="edit_no_match",+ message=f"old_string was not found in the file. The closest text starts at line {best + 1}:\n{excerpt}",+ line=best + 1,+ )diff --git a/products/canvas/backend/tests/test_build_service.py b/products/canvas/backend/tests/test_build_service.pyindex 3fecbd9403fb..d55720b26423 100644--- a/products/canvas/backend/tests/test_build_service.py+++ b/products/canvas/backend/tests/test_build_service.py@@ -369,6 +369,7 @@ class TestRunCanvasBuild(BuildServiceBaseTest):assert properties["outcome"] == outcomeassert properties["error_codes"] == error_codesassert properties["build_id"] == str(build.id)+ assert properties["canvas_kind"] == "freeform"class TestBuildDispatch(BuildServiceBaseTest):diff --git a/products/canvas/backend/tests/test_canvas_api.py b/products/canvas/backend/tests/test_canvas_api.pyindex 23ad7a89218e..fbf0e148dc0e 100644--- a/products/canvas/backend/tests/test_canvas_api.py+++ b/products/canvas/backend/tests/test_canvas_api.py@@ -64,6 +64,9 @@ class CanvasAPIBaseTest(APIBaseTest):enqueue = patch("products.canvas.backend.tasks.process_canvas_build.delay")self.enqueue = enqueue.start()self.addCleanup(enqueue.stop)+ no_build_wait = patch.object(build_service, "PUBLISH_BUILD_WAIT_SECONDS", 0)+ no_build_wait.start()+ self.addCleanup(no_build_wait.stop)with team_scope(self.team.id):self.channel = Channel.objects.create(team=self.team, name="general", created_by=self.user)@@ -739,6 +742,10 @@ class TestCanvasSourceAndPublish(CanvasAPIBaseTest):build = CanvasBuild.objects.unscoped().get(canvas_id=canvas_id)assert build.status == CanvasBuild.STATUS_QUEUEDself.enqueue.assert_called_once_with(self.team.id, str(build.id))+ assert response.json()["build"] == {"id": str(build.id), "build_status": "queued", "diagnostics": []}++ CanvasBuild.objects.unscoped().filter(id=build.id).update(status=CanvasBuild.STATUS_READY)+ assert build_service.wait_for_build_result(build).status == CanvasBuild.STATUS_READY# The multi-file project round-trips from the stored version.response = self.client.get(f"/api/projects/{self.team.id}/canvases/{canvas_id}/source/")@@ -746,6 +753,19 @@ class TestCanvasSourceAndPublish(CanvasAPIBaseTest):assert body["current_version_id"] == version_idassert body["project"]["files"]["src/extra.ts"] == "export const x = 1"+ def finish_build(queued: CanvasBuild) -> CanvasBuild:+ CanvasBuild.objects.unscoped().filter(id=queued.id).update(status=CanvasBuild.STATUS_READY)+ Canvas.objects.unscoped().filter(id=queued.canvas_id).update(published_build_id=queued.id)+ return CanvasBuild.objects.unscoped().get(id=queued.id)++ with patch.object(build_service, "wait_for_build_result", side_effect=finish_build):+ second = self._publish(+ canvas_id,+ self._project("export default function C() { return 2 }"),+ expected_current_version_id=version_id,+ )+ assert second.json()["canvas"]["published_build_id"] == second.json()["build"]["id"]+@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()@@ -835,6 +855,19 @@ class TestCanvasSourceAndPublish(CanvasAPIBaseTest):assert body["current_version_id"] == first.json()["current_version_id"]assert len(self.storage.objects) == 1+ stale_edit = self.client.post(+ f"/api/projects/{self.team.id}/canvases/{canvas_id}/edit/",+ {+ "operations": [+ {"op": "str_replace", "path": "src/canvas.tsx", "old_string": "return 2", "new_string": "return 3"}+ ],+ "expected_current_version_id": None,+ },+ format="json",+ )+ assert stale_edit.status_code == status.HTTP_409_CONFLICT+ assert stale_edit.json()["current_version_id"] == first.json()["current_version_id"]+def test_validation_errors_reject_publish(self):canvas_id = self._create_canvas()response = self._publish(canvas_id, self._project('import x from "left-pad"'))@@ -892,7 +925,25 @@ class TestCanvasSourceAndPublish(CanvasAPIBaseTest):response = self.client.post(f"/api/projects/{self.team.id}/canvases/{canvas_id}/edit/",{- "operations": [{"path": "src/added.ts", "content": "export {}"}],+ "operations": [+ {"path": "src/added.ts", "content": "export {}"},+ {+ "op": "str_replace",+ "path": "src/added.ts",+ "old_string": "export {}",+ "new_string": "export const y = 1",+ },+ {+ "type": "str_replace",+ "path": "src/canvas.tsx",+ "old_string": "return null",+ "new_string": 'return ph.loadInsight("abc123")',+ },+ ],+ "capabilities": {+ "posthog": {"insights": ["abc123"], "inlineQueries": False, "captureEvents": []},+ "network": {"origins": []},+ },"expected_current_version_id": version_id,},format="json",@@ -900,22 +951,53 @@ class TestCanvasSourceAndPublish(CanvasAPIBaseTest):assert response.status_code == status.HTTP_200_OK, response.json()source = self.client.get(f"/api/projects/{self.team.id}/canvases/{canvas_id}/source/").json()- assert source["project"]["files"]["src/added.ts"] == "export {}"- # The original component survives the per-file edit.- assert "src/canvas.tsx" in source["project"]["files"]+ assert source["project"]["files"]["src/added.ts"] == "export const y = 1"+ assert (+ source["project"]["files"]["src/canvas.tsx"]+ == 'export default function C() { return ph.loadInsight("abc123") }'+ )+ assert source["project"]["capabilities"]["posthog"]["insights"] == ["abc123"]def test_edit_delete_of_missing_file_400s(self):canvas_id = self._create_canvas()+ with patch("products.canvas.backend.presentation.views.report_user_action") as report:+ response = self.client.post(+ f"/api/projects/{self.team.id}/canvases/{canvas_id}/edit/",+ {+ "operations": [{"path": "src/nope.ts", "content": None}],+ "expected_current_version_id": None,+ },+ format="json",+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json()["diagnostics"][0]["code"] == "edit_target_missing"+ _user, event, properties = report.call_args.args+ assert event == "canvas edit rejected"+ assert properties["canvas_kind"] == "freeform"+ assert properties["error_codes"] == ["edit_target_missing"]+ assert properties["delete_operation_count"] == 1++ @parameterized.expand(+ [+ ("str_replace_without_new_string", {"op": "str_replace", "old_string": "export"}),+ ("new_string_without_op_or_old_string", {"new_string": "export const x = 2"}),+ ("misspelled_content_field", {"contents": "export const x = 2"}),+ ]+ )+ def test_incomplete_replacement_400s_and_keeps_the_file(self, _name: str, fields: dict[str, str]) -> None:+ canvas_id = self._create_canvas()+ project = self._project()+ project["files"]["src/extra.ts"] = "export const x = 1"+ version_id = self._publish(canvas_id, project, expected_current_version_id=None).json()["current_version_id"]+response = self.client.post(f"/api/projects/{self.team.id}/canvases/{canvas_id}/edit/",- {- "operations": [{"path": "src/nope.ts", "content": None}],- "expected_current_version_id": None,- },+ {"operations": [{"path": "src/extra.ts", **fields}], "expected_current_version_id": version_id},format="json",)assert response.status_code == status.HTTP_400_BAD_REQUEST- assert response.json()["diagnostics"][0]["code"] == "edit_target_missing"+ source = self.client.get(f"/api/projects/{self.team.id}/canvases/{canvas_id}/source/").json()+ assert source["project"]["files"]["src/extra.ts"] == "export const x = 1"def test_publish_clears_legacy_code(self):canvas_id = self._create_canvas()diff --git a/products/canvas/backend/tests/test_source_edits.py b/products/canvas/backend/tests/test_source_edits.pynew file mode 100644index 000000000000..74410885f1b9--- /dev/null+++ b/products/canvas/backend/tests/test_source_edits.py@@ -0,0 +1,79 @@+from typing import Any++from django.test import SimpleTestCase++from parameterized import parameterized++from products.canvas.backend.source import CANVAS_ENTRY_HTML+from products.canvas.backend.source_edits import apply_source_edits+from products.canvas.backend.tests.test_source import project++EDIT_SOURCE = "function Card() {\n return (\n <div>\n <Title>Users</Title>\n <Title>Users</Title>\n </div>\n );\n}\n"+++def replace(old: str, new: str, **extra: Any) -> dict[str, Any]:+ return {"op": "str_replace", "path": "src/card.tsx", "old_string": old, "new_string": new, **extra}+++class TestApplySourceEdits(SimpleTestCase):+ @parameterized.expand(+ [+ (+ "unique_exact_match",+ [replace("function Card() {", "function Panel() {")],+ EDIT_SOURCE.replace("function Card() {", "function Panel() {"),+ ),+ (+ "replace_all",+ [replace("Users", "People", replace_all=True)],+ EDIT_SOURCE.replace("Users", "People"),+ ),+ (+ "trailing_whitespace_and_crlf_ignored",+ [replace(" return ( \r\n <div>\r\n", " return (\n <section>\n")],+ EDIT_SOURCE.replace(" <div>", " <section>"),+ ),+ (+ "dropped_indentation_is_restored",+ [replace("return (\n <div>", "return (\n <main>")],+ EDIT_SOURCE.replace(" <div>", " <main>"),+ ),+ (+ "later_operation_sees_earlier_one",+ [replace("Card", "Panel"), replace("function Panel", "export function Panel")],+ EDIT_SOURCE.replace("function Card", "export function Panel"),+ ),+ ]+ )+ def test_str_replace_applies(self, _name, operations, expected):+ edited, diagnostics = apply_source_edits(project(files={"src/card.tsx": EDIT_SOURCE}), operations)+ assert diagnostics == []+ assert edited["files"]["src/card.tsx"] == expected++ @parameterized.expand(+ [+ ("exact_duplicate", [replace("<Title>Users</Title>", "<Title>People</Title>")], "edit_ambiguous_match", 4),+ ("loose_duplicate", [replace("<Title>Users</Title> ", "x")], "edit_ambiguous_match", 4),+ ("no_match_points_at_closest_line", [replace("return [", "return (")], "edit_no_match", 2),+ ("missing_file", [{**replace("a", "b"), "path": "src/nope.tsx"}], "edit_target_missing", None),+ (+ "rename_onto_existing_file",+ [{"op": "rename", "path": "src/card.tsx", "new_path": CANVAS_ENTRY_HTML}],+ "edit_target_exists",+ None,+ ),+ ]+ )+ def test_edit_that_cannot_apply_once_is_rejected(self, _name, operations, expected_code, expected_line):+ original = project(files={"src/card.tsx": EDIT_SOURCE})+ edited, diagnostics = apply_source_edits(original, operations)+ assert [entry["code"] for entry in diagnostics] == [expected_code]+ assert diagnostics[0].get("line") == expected_line+ assert original["files"]["src/card.tsx"] == EDIT_SOURCE++ def test_replace_all_that_would_exceed_the_file_limit_is_rejected(self) -> None:+ source = "a\n" * 200_000+ original = project(files={"src/card.tsx": source})+ edited, diagnostics = apply_source_edits(original, [replace("a", "x" * 4096, replace_all=True)])+ assert [entry["code"] for entry in diagnostics] == ["edit_too_large"]+ assert edited["files"]["src/card.tsx"] == sourcediff --git a/products/canvas/frontend/generated/api.schemas.ts b/products/canvas/frontend/generated/api.schemas.tsindex 5da40a0a133d..f04b812280b4 100644--- a/products/canvas/frontend/generated/api.schemas.ts+++ b/products/canvas/frontend/generated/api.schemas.ts@@ -796,24 +796,56 @@ export interface PaginatedCanvasDraftListApi {}/**- * One per-file edit: set a file's content, or delete it.+ * * `write` - Write+ * * `delete` - Delete+ * * `rename` - Rename+ * * `str_replace` - Str Replace+ */+export type CanvasSourceEditOpEnumApi = (typeof CanvasSourceEditOpEnumApi)[keyof typeof CanvasSourceEditOpEnumApi]++export const CanvasSourceEditOpEnumApi = {+ Write: 'write',+ Delete: 'delete',+ Rename: 'rename',+ StrReplace: 'str_replace',+} as const++/**+ * One file edit: replace text in a file, write a whole file, delete it, or rename it.*/export interface CanvasSourceEditOperationApi {- /** Project-relative path of the file to write or delete (e.g. "src/canvas.tsx"). */+ /** What to do. 'str_replace' replaces old_string with new_string inside the file: the default for changing an existing file. 'write' sets the file's complete content (new files, full rewrites). 'delete' removes the file. 'rename' moves it to new_path. When omitted, it follows the fields sent: old_string or new_string means 'str_replace', new_path means 'rename', non-null content means 'write', and content null means 'delete'. An operation with none of these fields is rejected.+ *+ * * `write` - Write+ * * `delete` - Delete+ * * `rename` - Rename+ * * `str_replace` - Str Replace */+ op?: CanvasSourceEditOpEnumApi+ /** Project-relative path of the file to edit (e.g. "src/canvas.tsx"). */path: string/**- * The file's complete new content. Null (or omitted) deletes the file.+ * For 'write': the file's complete new content.* @nullable*/content?: string | null+ /** For 'str_replace': the exact text to replace, copied from the file with a few surrounding lines so it matches one place only. If whitespace differs slightly, a unique line-by-line match is still accepted. */+ old_string?: string+ /** For 'str_replace': the text that replaces old_string. An empty string deletes old_string. */+ new_string?: string+ /** For 'str_replace': replace every exact match of old_string instead of requiring exactly one. */+ replace_all?: boolean+ /** For 'rename': the file's new project-relative path. */+ new_path?: string}/*** 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[]+ /** Edits applied in order to the canvas's current source project, all or nothing. May be empty when the edit only changes capabilities. */+ operations?: CanvasSourceEditOperationApi[]+ /** The project's complete new capabilities, replacing the current ones in the same publish. Send it when the change needs a capability the canvas does not declare yet, for example a new ph.state scope, insight, capture event, or network origin. Copy the current capabilities from canvas-source-retrieve and change only what you need. Omit to keep the current capabilities. */+ capabilities?: CanvasCapabilitiesApi/** Short description of the change, stored on the appended version history entry. */prompt?: string/**@@ -860,6 +892,23 @@ export interface CanvasSummaryApi {readonly url: string}+/**+ * The build a publish queued, as it stood when the response was sent.+ */+export interface CanvasPublishedBuildApi {+ /** The build's id. */+ id: string+ /** 'ready': the build finished. The canvas is live with this version when canvas.published_build_id equals this id; then you do not need canvas-builds-retrieve. 'failed': fix the error diagnostics and save again. 'queued' or 'building': poll canvas-builds-retrieve until the build is terminal.+ *+ * * `queued` - queued+ * * `building` - building+ * * `ready` - ready+ * * `failed` - failed */+ build_status: BuildStatusEnumApi+ /** Structured diagnostics recorded by the build (errors explain a failed status). */+ diagnostics: CanvasDiagnosticApi[]+}+/*** Result of a successful source-project publish.*/@@ -870,6 +919,8 @@ export interface CanvasSourcePublishResponseApi {current_version_id: string/** Advisory (warning-severity) diagnostics recorded for the published project. */diagnostics: CanvasDiagnosticApi[]+ /** The queued build. The server waits a few seconds for it, so it is often already terminal. */+ build: CanvasPublishedBuildApi}/**diff --git a/products/canvas/frontend/generated/api.ts b/products/canvas/frontend/generated/api.tsindex 73fa45edf999..192529f0625c 100644--- a/products/canvas/frontend/generated/api.ts+++ b/products/canvas/frontend/generated/api.ts@@ -343,11 +343,11 @@ export const getCanvasesEditCreateUrl = (projectId: string, id: string) => {}/**- * Publish per-file edits against the canvas's current source project.+ * Publish file edits against the canvas's current source project.*- * Diff-aware alternative to sending the complete project: each operation- * sets a file's content or (content null) deletes it, applied to the head- * the caller read. `expected_current_version_id` is mandatory here —+ * Diff-aware alternative to sending the complete project: operations+ * replace text inside a file, write, delete, or rename files, applied in+ * order to the head the caller read. `expected_current_version_id` is mandatory here —* relative edits against an unverified base could silently merge into* someone else's newer work.*/diff --git a/products/canvas/frontend/generated/api.zod.ts b/products/canvas/frontend/generated/api.zod.tsindex 38cf1674be78..895e1ed76a14 100644--- a/products/canvas/frontend/generated/api.zod.ts+++ b/products/canvas/frontend/generated/api.zod.ts@@ -386,14 +386,42 @@ export const CanvasesDraftCreateBody = /* @__PURE__ */ zod.describe('Payload for staging a complete source project as a draft build.')/**- * Publish per-file edits against the canvas's current source project.+ * Publish file edits against the canvas's current source project.*- * Diff-aware alternative to sending the complete project: each operation- * sets a file's content or (content null) deletes it, applied to the head- * the caller read. `expected_current_version_id` is mandatory here —+ * Diff-aware alternative to sending the complete project: operations+ * replace text inside a file, write, delete, or rename files, applied in+ * order to the head the caller read. `expected_current_version_id` is mandatory here —* relative edits against an unverified base could silently merge into* someone else's newer work.*/+export const canvasesEditCreateBodyOperationsItemReplaceAllDefault = false+export const canvasesEditCreateBodyCapabilitiesOnePosthogInsightsItemMax = 128++export const canvasesEditCreateBodyCapabilitiesOnePosthogInsightsMax = 100++export const canvasesEditCreateBodyCapabilitiesOnePosthogCaptureEventsItemMax = 200++export const canvasesEditCreateBodyCapabilitiesOnePosthogCaptureEventsMax = 100++export const canvasesEditCreateBodyCapabilitiesOnePosthogStateMax = 2++export const canvasesEditCreateBodyCapabilitiesOnePosthogActionsItemMax = 64++export const canvasesEditCreateBodyCapabilitiesOnePosthogActionsMax = 32++export const canvasesEditCreateBodyCapabilitiesOnePosthogAgentRequestsDefault = false+export const canvasesEditCreateBodyCapabilitiesOneNetworkOriginsItemMax = 2048++export const canvasesEditCreateBodyCapabilitiesOneNetworkOriginsMax = 20++export const canvasesEditCreateBodyCapabilitiesOneConnectorsItemProviderMax = 300++export const canvasesEditCreateBodyCapabilitiesOneConnectorsItemToolsItemMax = 200++export const canvasesEditCreateBodyCapabilitiesOneConnectorsItemToolsMax = 64++export const canvasesEditCreateBodyCapabilitiesOneConnectorsMax = 20+export const canvasesEditCreateBodyNameMax = 400export const CanvasesEditCreateBody = /* @__PURE__ */ zod@@ -402,19 +430,115 @@ export const CanvasesEditCreateBody = /* @__PURE__ */ zod.array(zod.object({+ op: zod+ .enum(['write', 'delete', 'rename', 'str_replace'])+ .describe(+ '\* `write` - Write\n\* `delete` - Delete\n\* `rename` - Rename\n\* `str_replace` - Str Replace'+ )+ .optional()+ .describe(+ "What to do. 'str_replace' replaces old_string with new_string inside the file: the default for changing an existing file. 'write' sets the file's complete content (new files, full rewrites). 'delete' removes the file. 'rename' moves it to new_path. When omitted, it follows the fields sent: old_string or new_string means 'str_replace', new_path means 'rename', non-null content means 'write', and content null means 'delete'. An operation with none of these fields is rejected.\n\n\* `write` - Write\n\* `delete` - Delete\n\* `rename` - Rename\n\* `str_replace` - Str Replace"+ ),path: zod.string()+ .describe('Project-relative path of the file to edit (e.g. \"src\/canvas.tsx\").'),+ content: zod.string().nullish().describe("For 'write': the file's complete new content."),+ old_string: zod+ .string()+ .optional()+ .describe(+ "For 'str_replace': the exact text to replace, copied from the file with a few surrounding lines so it matches one place only. If whitespace differs slightly, a unique line-by-line match is still accepted."+ ),+ new_string: zod+ .string()+ .optional()+ .describe(+ "For 'str_replace': the text that replaces old_string. An empty string deletes old_string."+ ),+ replace_all: zod+ .boolean()+ .default(canvasesEditCreateBodyOperationsItemReplaceAllDefault).describe(- 'Project-relative path of the file to write or delete (e.g. \"src\/canvas.tsx\").'+ "For 'str_replace': replace every exact match of old_string instead of requiring exactly one."),- content: zod+ new_path: zod.string()- .nullish()- .describe("The file's complete new content. Null (or omitted) deletes the file."),+ .optional()+ .describe("For 'rename': the file's new project-relative path."),})- .describe("One per-file edit: set a file's content, or delete it.")+ .describe('One file edit: replace text in a file, write a whole file, delete it, or rename it.'))- .describe("Edits applied in order to the canvas's current source project."),+ .optional()+ .describe(+ "Edits applied in order to the canvas's current source project, all or nothing. May be empty when the edit only changes capabilities."+ ),+ capabilities: zod+ .object({+ posthog: zod.object({+ insights: zod+ .array(zod.string().max(canvasesEditCreateBodyCapabilitiesOnePosthogInsightsItemMax))+ .max(canvasesEditCreateBodyCapabilitiesOnePosthogInsightsMax),+ inlineQueries: zod.boolean(),+ captureEvents: zod+ .array(zod.string().max(canvasesEditCreateBodyCapabilitiesOnePosthogCaptureEventsItemMax))+ .max(canvasesEditCreateBodyCapabilitiesOnePosthogCaptureEventsMax),+ state: zod+ .array(zod.enum(['user', 'shared']).describe('\* `user` - user\n\* `shared` - shared'))+ .max(canvasesEditCreateBodyCapabilitiesOnePosthogStateMax)+ .optional()+ .describe(+ "State scopes the canvas may use via ph.state: 'user' (private to each viewer) and\/or 'shared' (one value per canvas, team-visible)."+ ),+ actions: zod+ .array(zod.string().max(canvasesEditCreateBodyCapabilitiesOnePosthogActionsItemMax))+ .max(canvasesEditCreateBodyCapabilitiesOnePosthogActionsMax)+ .optional()+ .describe(+ "Registered action verbs the canvas may invoke via ph.actions (e.g. 'annotations.create', 'tasks.create'). Each executes as the viewer; declaring one shows it in the promote review."+ ),+ agentRequests: zod+ .boolean()+ .default(canvasesEditCreateBodyCapabilitiesOnePosthogAgentRequestsDefault),+ }),+ network: zod.object({+ origins: zod+ .array(zod.url().max(canvasesEditCreateBodyCapabilitiesOneNetworkOriginsItemMax))+ .max(canvasesEditCreateBodyCapabilitiesOneNetworkOriginsMax),+ }),+ connectors: zod+ .array(+ zod+ .object({+ provider: zod+ .string()+ .max(canvasesEditCreateBodyCapabilitiesOneConnectorsItemProviderMax)+ .describe(+ "Connector provider id: a native provider such as 'github', or 'mcp:<server host>' (e.g. 'mcp:mcp.calendly.com') for a server the viewer connected in the MCP store."+ ),+ tools: zod+ .array(+ zod+ .string()+ .max(canvasesEditCreateBodyCapabilitiesOneConnectorsItemToolsItemMax)+ )+ .min(1)+ .max(canvasesEditCreateBodyCapabilitiesOneConnectorsItemToolsMax)+ .describe('Tool names the canvas may call on this provider. Read-only tools only.'),+ })+ .describe(+ 'One provider a canvas may call through ph.connectors, with the tools it may use.'+ )+ )+ .max(canvasesEditCreateBodyCapabilitiesOneConnectorsMax)+ .optional()+ .describe(+ "Third-party providers the canvas reads through ph.connectors, each with the tools it may call. Every call runs with the viewer's own connection; declaring one shows it in the promote review."+ ),+ })+ .optional()+ .describe(+ "The project's complete new capabilities, replacing the current ones in the same publish. Send it when the change needs a capability the canvas does not declare yet, for example a new ph.state scope, insight, capture event, or network origin. Copy the current capabilities from canvas-source-retrieve and change only what you need. Omit to keep the current capabilities."+ ),prompt: zod.string().optional()diff --git a/products/canvas/mcp/tools.yaml b/products/canvas/mcp/tools.yamlindex 345fdc4d323c..60474a97b3ef 100644--- a/products/canvas/mcp/tools.yaml+++ b/products/canvas/mcp/tools.yaml@@ -24,7 +24,8 @@ tools:recent builds with their status (queued/building/ready/failed) and structured diagnostics. A publish queuesa build; poll this until the build you queued is terminal — `ready` (the live pointer advances) or `failed`(fix the error diagnostics and publish again; the last good build stays live). Do not finish a canvas task- while its build is still queued or building.+ while its build is still queued or building. A publish or edit response already carries its build status, so+ call this only when that status was `queued` or `building`.param_overrides:id:description: ID of the canvas whose builds to read.@@ -132,13 +133,25 @@ tools:idempotent: falsetitle: Edit canvas source filesdescription: >- 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.+ Change an existing canvas by sending only the edits, not the whole project. This is the default way to save+ a change to a canvas that already has source. Operations apply in order and all or nothing: `str_replace`+ (replace `old_string` with `new_string` in `path`; copy `old_string` from the file with a few surrounding+ lines so it matches exactly one place, or set `replace_all`), `write` (a file's complete `content`, for new+ files or full rewrites), `delete`, and `rename` (to `new_path`). When the change needs a capability the+ canvas does not declare yet (for example a new `ph.state` scope), also send `capabilities` with the complete+ new capabilities in the same edit; do not switch to canvas-publish-create for that. Example operation:+ {"op": "str_replace", "path": "src/canvas.tsx", "old_string": "<CardTitle>Users</CardTitle>", "new_string":+ "<CardTitle>Daily active users</CardTitle>"}. A 400 lists each failed operation by index: `edit_no_match`+ shows the closest lines of the file, `edit_ambiguous_match` lists the matching lines. Fix those operations+ and send the edit again; if a replacement fails twice, `write` the whole file instead.+ `expected_current_version_id` is REQUIRED (from canvas-source-retrieve, or the `current_version_id` a+ previous edit returned; null only for a never-published canvas). A stale base is rejected with 409+ version_conflict: re-read the source and edit again. The edited project is validated, published, and built+ like canvas-publish-create. The response's `build` carries the build status: `ready` means the build+ finished, and the canvas shows it when `canvas.published_build_id` is its id, so do not call+ canvas-builds-retrieve; `failed` lists the build errors to fix; poll canvas-builds-retrieve only while it is+ `queued` or `building`. Stage 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.@@ -291,10 +304,11 @@ 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.- 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+ Publish the COMPLETE source project of a canvas as its new head version and queue a server-side build. Use+ it for a canvas's first version or to replace the whole project; for a change to an existing canvas, send+ only the edits with canvas-edit-create. Publishing goes live immediately; 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. Declare@@ -302,7 +316,10 @@ tools:project that shows PostHog data must make every figure verifiable before publishing: an insight-backedmetric links its saved insight (ph.openExternal with a URL from generate-app-url); an ad-hoc ph.query figureexposes 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.+ this tool is what saves it. The response's `build` carries the build status: `ready` means the build+ finished, and the canvas shows it when `canvas.published_build_id` is its id, so do not call+ canvas-builds-retrieve; `failed` lists the build errors to fix; poll canvas-builds-retrieve only while it is+ `queued` or `building`.param_overrides:id:description: ID of the canvas whose source to publish.@@ -340,11 +357,10 @@ tools:idempotent: truetitle: Read canvas source projectdescription: >- Read a canvas's source project and its `current_version_id`. Always call this before editing a canvas: edit- the returned files, then publish the complete project with canvas-publish-create, passing the- `current_version_id` you read as `expected_current_version_id` so concurrent edits are not overwritten.- Canvases that predate multi-file projects are presented as a synthetic project whose `src/canvas.tsx` holds- the React component.+ Read a canvas's source project and its `current_version_id`. Always call this before editing a canvas, then+ save the change with canvas-edit-create (send only the edits), passing the `current_version_id` you read as+ `expected_current_version_id` so concurrent edits are not overwritten. Canvases that predate multi-file+ projects are presented as a synthetic project whose `src/canvas.tsx` holds the React component.param_overrides:id:description: ID of the canvas whose source to read.diff --git a/products/canvas/skills/building-canvases/SKILL.md b/products/canvas/skills/building-canvases/SKILL.mdindex 0033c9a2bb07..dc1ac37ea73d 100644--- a/products/canvas/skills/building-canvases/SKILL.md+++ b/products/canvas/skills/building-canvases/SKILL.md@@ -122,13 +122,14 @@ matching shape above. The pattern is a hint; the user's actual request remains a4. 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): 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`.+ - **Already live** (`current_version_id` is set): send only the edits with `canvas-edit-create`, using `str_replace` operations for changes inside a file.+ Pass the live `current_version_id` as `expected_current_version_id`.+ Publish the complete project with `canvas-publish-create` only to replace the whole project.- Stage a draft with `canvas-draft-create` only when the user asked for a draft, a preview, ora 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`+5. **Wait for the build** — drafts and publishes alike queue one. A publish or edit response+ already carries `build.build_status`; use it when it is `ready` or `failed`. Otherwise 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.diff --git a/products/canvas/skills/validating-and-publishing-canvases/SKILL.md b/products/canvas/skills/validating-and-publishing-canvases/SKILL.mdindex d9ef7b44ffb8..0f8e59d81e4e 100644--- a/products/canvas/skills/validating-and-publishing-canvases/SKILL.md+++ b/products/canvas/skills/validating-and-publishing-canvases/SKILL.md@@ -90,10 +90,22 @@ asked for a draft, a preview, or a review step — see "Draft, then promote" belTwo 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- file's complete content, or deletes it with `content: null`). Prefer this for small changes to a- large project; the guard is mandatory here because a diff's meaning depends on its base.+- **Edits** — `canvas-edit-create` with `operations`. This is the default for any change to a canvas that already has source.+ The guard is mandatory here because an edit's meaning depends on its base.+- **Whole project** — `canvas-publish-create` with the complete `project`, for a first version or to replace everything.++For an edit with `canvas-edit-create`:++- Use `str_replace` for a change inside a file: `old_string` is text copied from the file you read, with a few surrounding lines so it matches exactly one place.+ Set `replace_all: true` to change every match, for example a rename.+- Use `write` with the complete `content` for a new file or a full rewrite, `delete` to remove a file, and `rename` with `new_path` to move one.+- When the change needs a new capability, for example a `ph.state` scope, also send `capabilities` with the complete new capabilities (the current ones plus the addition) in the same edit.+ Do not switch to `canvas-publish-create` for that.+- Put every operation of one change into one call. They apply in order, and the whole edit is rejected if any operation fails.+- A 400 lists each failed operation by index. `edit_no_match` shows the closest lines of the file and `edit_ambiguous_match` lists the lines that match.+ Fix those operations from the diagnostic and send the edit again. If one replacement fails twice, `write` that whole file instead.+- The response returns the new `current_version_id`. Pass it to the next edit.+ When you published or edited the canvas earlier in this session, do not call `canvas-source-retrieve` before the next edit: you already know the source, and a 409 `version_conflict` tells you when someone else changed it.For a whole-project publish with `canvas-publish-create`:@@ -112,8 +124,10 @@ The response returns the new `current_version_id`.## After publishing: wait for the buildA publish queues a server-side build of the version. **The canvas does not update until the build-is ready, and nobody else is watching the result — you own it.** Poll `canvas-builds-retrieve`-every few seconds (up to ~2 minutes) until the build you queued is terminal:+is ready, and nobody else is watching the result — you own it.** The publish or edit response+already carries `build.build_status`. When it is `ready` or `failed`, act on it without another call.+Only while it is `queued` or `building`, poll `canvas-builds-retrieve` every few seconds (up to ~2 minutes)+until the build you queued is terminal:- `queued`/`building` — in progress; poll again shortly.- `ready` — the canvas's `published_build_id` advances to this build (unless a newer publishdiff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex f694aee5e2b9..b94f6a917086 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -1430,7 +1430,7 @@"feature_flag": "product-business-knowledge"},"canvas-builds-retrieve": {- "description": "Read a canvas's build lifecycle: `published_build_id` (the live build), `current_version_id`, and the most recent builds with their status (queued/building/ready/failed) and structured diagnostics. A publish queues a build; poll this until the build you queued is terminal — `ready` (the live pointer advances) or `failed` (fix the error diagnostics and publish again; the last good build stays live). Do not finish a canvas task while its build is still queued or building.",+ "description": "Read a canvas's build lifecycle: `published_build_id` (the live build), `current_version_id`, and the most recent builds with their status (queued/building/ready/failed) and structured diagnostics. A publish queues a build; poll this until the build you queued is terminal — `ready` (the live pointer advances) or `failed` (fix the error diagnostics and publish again; the last good build stays live). Do not finish a canvas task while its build is still queued or building. A publish or edit response already carries its build status, so call this only when that status was `queued` or `building`.","category": "Canvas","feature": "canvas","summary": "Read canvas build status",@@ -1500,7 +1500,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, 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.",+ "description": "Change an existing canvas by sending only the edits, not the whole project. This is the default way to save a change to a canvas that already has source. Operations apply in order and all or nothing: `str_replace` (replace `old_string` with `new_string` in `path`; copy `old_string` from the file with a few surrounding lines so it matches exactly one place, or set `replace_all`), `write` (a file's complete `content`, for new files or full rewrites), `delete`, and `rename` (to `new_path`). When the change needs a capability the canvas does not declare yet (for example a new `ph.state` scope), also send `capabilities` with the complete new capabilities in the same edit; do not switch to canvas-publish-create for that. Example operation: {\"op\": \"str_replace\", \"path\": \"src/canvas.tsx\", \"old_string\": \"<CardTitle>Users</CardTitle>\", \"new_string\": \"<CardTitle>Daily active users</CardTitle>\"}. A 400 lists each failed operation by index: `edit_no_match` shows the closest lines of the file, `edit_ambiguous_match` lists the matching lines. Fix those operations and send the edit again; if a replacement fails twice, `write` the whole file instead. `expected_current_version_id` is REQUIRED (from canvas-source-retrieve, or the `current_version_id` a previous edit returned; null only for a never-published canvas). A stale base is rejected with 409 version_conflict: re-read the source and edit again. The edited project is validated, published, and built like canvas-publish-create. The response's `build` carries the build status: `ready` means the build finished, and the canvas shows it when `canvas.published_build_id` is its id, so do not call canvas-builds-retrieve; `failed` lists the build errors to fix; poll canvas-builds-retrieve only while it is `queued` or `building`. Stage 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",@@ -1598,7 +1598,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 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.",+ "description": "Publish the COMPLETE source project of a canvas as its new head version and queue a server-side build. Use it for a canvas's first version or to replace the whole project; for a change to an existing canvas, send only the edits with canvas-edit-create. Publishing goes live immediately; 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. The response's `build` carries the build status: `ready` means the build finished, and the canvas shows it when `canvas.published_build_id` is its id, so do not call canvas-builds-retrieve; `failed` lists the build errors to fix; poll canvas-builds-retrieve only while it is `queued` or `building`.","category": "Canvas","feature": "canvas","summary": "Publish canvas source project",@@ -1626,7 +1626,7 @@}},"canvas-source-retrieve": {- "description": "Read a canvas's source project and its `current_version_id`. Always call this before editing a canvas: edit the returned files, then publish the complete project with canvas-publish-create, passing the `current_version_id` you read as `expected_current_version_id` so concurrent edits are not overwritten. Canvases that predate multi-file projects are presented as a synthetic project whose `src/canvas.tsx` holds the React component.",+ "description": "Read a canvas's source project and its `current_version_id`. Always call this before editing a canvas, then save the change with canvas-edit-create (send only the edits), passing the `current_version_id` you read as `expected_current_version_id` so concurrent edits are not overwritten. Canvases that predate multi-file projects are presented as a synthetic project whose `src/canvas.tsx` holds the React component.","category": "Canvas","feature": "canvas","summary": "Read canvas source project",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 43746cfd84ba..f11dec3a647a 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -1445,7 +1445,7 @@"feature_flag": "product-business-knowledge"},"canvas-builds-retrieve": {- "description": "Read a canvas's build lifecycle: `published_build_id` (the live build), `current_version_id`, and the most recent builds with their status (queued/building/ready/failed) and structured diagnostics. A publish queues a build; poll this until the build you queued is terminal — `ready` (the live pointer advances) or `failed` (fix the error diagnostics and publish again; the last good build stays live). Do not finish a canvas task while its build is still queued or building.",+ "description": "Read a canvas's build lifecycle: `published_build_id` (the live build), `current_version_id`, and the most recent builds with their status (queued/building/ready/failed) and structured diagnostics. A publish queues a build; poll this until the build you queued is terminal — `ready` (the live pointer advances) or `failed` (fix the error diagnostics and publish again; the last good build stays live). Do not finish a canvas task while its build is still queued or building. A publish or edit response already carries its build status, so call this only when that status was `queued` or `building`.","category": "Canvas","feature": "canvas","summary": "Read canvas build status",@@ -1515,7 +1515,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, 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.",+ "description": "Change an existing canvas by sending only the edits, not the whole project. This is the default way to save a change to a canvas that already has source. Operations apply in order and all or nothing: `str_replace` (replace `old_string` with `new_string` in `path`; copy `old_string` from the file with a few surrounding lines so it matches exactly one place, or set `replace_all`), `write` (a file's complete `content`, for new files or full rewrites), `delete`, and `rename` (to `new_path`). When the change needs a capability the canvas does not declare yet (for example a new `ph.state` scope), also send `capabilities` with the complete new capabilities in the same edit; do not switch to canvas-publish-create for that. Example operation: {\"op\": \"str_replace\", \"path\": \"src/canvas.tsx\", \"old_string\": \"<CardTitle>Users</CardTitle>\", \"new_string\": \"<CardTitle>Daily active users</CardTitle>\"}. A 400 lists each failed operation by index: `edit_no_match` shows the closest lines of the file, `edit_ambiguous_match` lists the matching lines. Fix those operations and send the edit again; if a replacement fails twice, `write` the whole file instead. `expected_current_version_id` is REQUIRED (from canvas-source-retrieve, or the `current_version_id` a previous edit returned; null only for a never-published canvas). A stale base is rejected with 409 version_conflict: re-read the source and edit again. The edited project is validated, published, and built like canvas-publish-create. The response's `build` carries the build status: `ready` means the build finished, and the canvas shows it when `canvas.published_build_id` is its id, so do not call canvas-builds-retrieve; `failed` lists the build errors to fix; poll canvas-builds-retrieve only while it is `queued` or `building`. Stage 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",@@ -1613,7 +1613,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 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.",+ "description": "Publish the COMPLETE source project of a canvas as its new head version and queue a server-side build. Use it for a canvas's first version or to replace the whole project; for a change to an existing canvas, send only the edits with canvas-edit-create. Publishing goes live immediately; 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. The response's `build` carries the build status: `ready` means the build finished, and the canvas shows it when `canvas.published_build_id` is its id, so do not call canvas-builds-retrieve; `failed` lists the build errors to fix; poll canvas-builds-retrieve only while it is `queued` or `building`.","category": "Canvas","feature": "canvas","summary": "Publish canvas source project",@@ -1641,7 +1641,7 @@}},"canvas-source-retrieve": {- "description": "Read a canvas's source project and its `current_version_id`. Always call this before editing a canvas: edit the returned files, then publish the complete project with canvas-publish-create, passing the `current_version_id` you read as `expected_current_version_id` so concurrent edits are not overwritten. Canvases that predate multi-file projects are presented as a synthetic project whose `src/canvas.tsx` holds the React component.",+ "description": "Read a canvas's source project and its `current_version_id`. Always call this before editing a canvas, then save the change with canvas-edit-create (send only the edits), passing the `current_version_id` you read as `expected_current_version_id` so concurrent edits are not overwritten. Canvases that predate multi-file projects are presented as a synthetic project whose `src/canvas.tsx` holds the React component.","category": "Canvas","feature": "canvas","summary": "Read canvas source project",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 8b8789169560..674a24e0f081 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -18657,6 +18657,23 @@ export namespace Schemas {expected_current_version_id: string;}+ /**+ * The build a publish queued, as it stood when the response was sent.+ */+ export interface CanvasPublishedBuild {+ /** The build's id. */+ id: string;+ /** 'ready': the build finished. The canvas is live with this version when canvas.published_build_id equals this id; then you do not need canvas-builds-retrieve. 'failed': fix the error diagnostics and save again. 'queued' or 'building': poll canvas-builds-retrieve until the build is terminal.+ *+ * * `queued` - queued+ * * `building` - building+ * * `ready` - ready+ * * `failed` - failed */+ build_status: BuildStatusEnum;+ /** Structured diagnostics recorded by the build (errors explain a failed status). */+ diagnostics: CanvasDiagnostic[];+ }+/*** Payload for reporting a runtime error observed while rendering a canvas build.*/@@ -18804,24 +18821,57 @@ export namespace Schemas {}/**- * One per-file edit: set a file's content, or delete it.+ * * `write` - Write+ * * `delete` - Delete+ * * `rename` - Rename+ * * `str_replace` - Str Replace+ */+ export type CanvasSourceEditOpEnum = typeof CanvasSourceEditOpEnum[keyof typeof CanvasSourceEditOpEnum];+++ export const CanvasSourceEditOpEnum = {+ Write: 'write',+ Delete: 'delete',+ Rename: 'rename',+ StrReplace: 'str_replace',+ } as const;++ /**+ * One file edit: replace text in a file, write a whole file, delete it, or rename it.*/export interface CanvasSourceEditOperation {- /** Project-relative path of the file to write or delete (e.g. "src/canvas.tsx"). */+ /** What to do. 'str_replace' replaces old_string with new_string inside the file: the default for changing an existing file. 'write' sets the file's complete content (new files, full rewrites). 'delete' removes the file. 'rename' moves it to new_path. When omitted, it follows the fields sent: old_string or new_string means 'str_replace', new_path means 'rename', non-null content means 'write', and content null means 'delete'. An operation with none of these fields is rejected.+ *+ * * `write` - Write+ * * `delete` - Delete+ * * `rename` - Rename+ * * `str_replace` - Str Replace */+ op?: CanvasSourceEditOpEnum;+ /** Project-relative path of the file to edit (e.g. "src/canvas.tsx"). */path: string;/**- * The file's complete new content. Null (or omitted) deletes the file.+ * For 'write': the file's complete new content.* @nullable*/content?: string | null;+ /** For 'str_replace': the exact text to replace, copied from the file with a few surrounding lines so it matches one place only. If whitespace differs slightly, a unique line-by-line match is still accepted. */+ old_string?: string;+ /** For 'str_replace': the text that replaces old_string. An empty string deletes old_string. */+ new_string?: string;+ /** For 'str_replace': replace every exact match of old_string instead of requiring exactly one. */+ replace_all?: boolean;+ /** For 'rename': the file's new project-relative path. */+ new_path?: string;}/*** Payload for publishing per-file edits against the canvas's current source.*/export interface CanvasSourceEdit {- /** Edits applied in order to the canvas's current source project. */- operations: CanvasSourceEditOperation[];+ /** Edits applied in order to the canvas's current source project, all or nothing. May be empty when the edit only changes capabilities. */+ operations?: CanvasSourceEditOperation[];+ /** The project's complete new capabilities, replacing the current ones in the same publish. Send it when the change needs a capability the canvas does not declare yet, for example a new ph.state scope, insight, capture event, or network origin. Copy the current capabilities from canvas-source-retrieve and change only what you need. Omit to keep the current capabilities. */+ capabilities?: CanvasCapabilities;/** Short description of the change, stored on the appended version history entry. */prompt?: string;/**@@ -18878,6 +18928,8 @@ export namespace Schemas {current_version_id: string;/** Advisory (warning-severity) diagnostics recorded for the published project. */diagnostics: CanvasDiagnostic[];+ /** The queued build. The server waits a few seconds for it, so it is often already terminal. */+ build: CanvasPublishedBuild;}/**diff --git a/services/mcp/src/generated/canvas/api.ts b/services/mcp/src/generated/canvas/api.tsindex a82067ab2181..c474b24655b0 100644--- a/services/mcp/src/generated/canvas/api.ts+++ b/services/mcp/src/generated/canvas/api.ts@@ -420,11 +420,11 @@ export const CanvasesDraftsRetrieveQueryParams = () => zod.object({})/**- * Publish per-file edits against the canvas's current source project.+ * Publish file edits against the canvas's current source project.*- * Diff-aware alternative to sending the complete project: each operation- * sets a file's content or (content null) deletes it, applied to the head- * the caller read. `expected_current_version_id` is mandatory here —+ * Diff-aware alternative to sending the complete project: operations+ * replace text inside a file, write, delete, or rename files, applied in+ * order to the head the caller read. `expected_current_version_id` is mandatory here —* relative edits against an unverified base could silently merge into* someone else's newer work.*/@@ -437,6 +437,34 @@ export const CanvasesEditCreateParams = () => zod.object({),})+export const canvasesEditCreateBodyOperationsItemReplaceAllDefault = false+export const canvasesEditCreateBodyCapabilitiesOnePosthogInsightsItemMax = 128++export const canvasesEditCreateBodyCapabilitiesOnePosthogInsightsMax = 100++export const canvasesEditCreateBodyCapabilitiesOnePosthogCaptureEventsItemMax = 200++export const canvasesEditCreateBodyCapabilitiesOnePosthogCaptureEventsMax = 100++export const canvasesEditCreateBodyCapabilitiesOnePosthogStateMax = 2++export const canvasesEditCreateBodyCapabilitiesOnePosthogActionsItemMax = 64++export const canvasesEditCreateBodyCapabilitiesOnePosthogActionsMax = 32++export const canvasesEditCreateBodyCapabilitiesOnePosthogAgentRequestsDefault = false+export const canvasesEditCreateBodyCapabilitiesOneNetworkOriginsItemMax = 2048++export const canvasesEditCreateBodyCapabilitiesOneNetworkOriginsMax = 20++export const canvasesEditCreateBodyCapabilitiesOneConnectorsItemProviderMax = 300++export const canvasesEditCreateBodyCapabilitiesOneConnectorsItemToolsItemMax = 200++export const canvasesEditCreateBodyCapabilitiesOneConnectorsItemToolsMax = 64++export const canvasesEditCreateBodyCapabilitiesOneConnectorsMax = 20+export const canvasesEditCreateBodyNameMax = 400export const CanvasesEditCreateBody = () => zod@@ -445,19 +473,115 @@ export const CanvasesEditCreateBody = () => zod.array(zod.object({+ op: zod+ .enum(['write', 'delete', 'rename', 'str_replace'])+ .describe(+ '\* `write` - Write\n\* `delete` - Delete\n\* `rename` - Rename\n\* `str_replace` - Str Replace'+ )+ .optional()+ .describe(+ "What to do. 'str_replace' replaces old_string with new_string inside the file: the default for changing an existing file. 'write' sets the file's complete content (new files, full rewrites). 'delete' removes the file. 'rename' moves it to new_path. When omitted, it follows the fields sent: old_string or new_string means 'str_replace', new_path means 'rename', non-null content means 'write', and content null means 'delete'. An operation with none of these fields is rejected.\n\n\* `write` - Write\n\* `delete` - Delete\n\* `rename` - Rename\n\* `str_replace` - Str Replace"+ ),path: zod.string()+ .describe('Project-relative path of the file to edit (e.g. \"src\/canvas.tsx\").'),+ content: zod.string().nullish().describe("For 'write': the file's complete new content."),+ old_string: zod+ .string()+ .optional()+ .describe(+ "For 'str_replace': the exact text to replace, copied from the file with a few surrounding lines so it matches one place only. If whitespace differs slightly, a unique line-by-line match is still accepted."+ ),+ new_string: zod+ .string()+ .optional()+ .describe(+ "For 'str_replace': the text that replaces old_string. An empty string deletes old_string."+ ),+ replace_all: zod+ .boolean()+ .default(canvasesEditCreateBodyOperationsItemReplaceAllDefault).describe(- 'Project-relative path of the file to write or delete (e.g. \"src\/canvas.tsx\").'+ "For 'str_replace': replace every exact match of old_string instead of requiring exactly one."),- content: zod+ new_path: zod.string()- .nullish()- .describe("The file's complete new content. Null (or omitted) deletes the file."),+ .optional()+ .describe("For 'rename': the file's new project-relative path."),})- .describe("One per-file edit: set a file's content, or delete it.")+ .describe('One file edit: replace text in a file, write a whole file, delete it, or rename it.'))- .describe("Edits applied in order to the canvas's current source project."),+ .optional()+ .describe(+ "Edits applied in order to the canvas's current source project, all or nothing. May be empty when the edit only changes capabilities."+ ),+ capabilities: zod+ .object({+ posthog: zod.object({+ insights: zod+ .array(zod.string().max(canvasesEditCreateBodyCapabilitiesOnePosthogInsightsItemMax))+ .max(canvasesEditCreateBodyCapabilitiesOnePosthogInsightsMax),+ inlineQueries: zod.boolean(),+ captureEvents: zod+ .array(zod.string().max(canvasesEditCreateBodyCapabilitiesOnePosthogCaptureEventsItemMax))+ .max(canvasesEditCreateBodyCapabilitiesOnePosthogCaptureEventsMax),+ state: zod+ .array(zod.enum(['user', 'shared']).describe('\* `user` - user\n\* `shared` - shared'))+ .max(canvasesEditCreateBodyCapabilitiesOnePosthogStateMax)+ .optional()+ .describe(+ "State scopes the canvas may use via ph.state: 'user' (private to each viewer) and\/or 'shared' (one value per canvas, team-visible)."+ ),+ actions: zod+ .array(zod.string().max(canvasesEditCreateBodyCapabilitiesOnePosthogActionsItemMax))+ .max(canvasesEditCreateBodyCapabilitiesOnePosthogActionsMax)+ .optional()+ .describe(+ "Registered action verbs the canvas may invoke via ph.actions (e.g. 'annotations.create', 'tasks.create'). Each executes as the viewer; declaring one shows it in the promote review."+ ),+ agentRequests: zod+ .boolean()+ .default(canvasesEditCreateBodyCapabilitiesOnePosthogAgentRequestsDefault),+ }),+ network: zod.object({+ origins: zod+ .array(zod.url().max(canvasesEditCreateBodyCapabilitiesOneNetworkOriginsItemMax))+ .max(canvasesEditCreateBodyCapabilitiesOneNetworkOriginsMax),+ }),+ connectors: zod+ .array(+ zod+ .object({+ provider: zod+ .string()+ .max(canvasesEditCreateBodyCapabilitiesOneConnectorsItemProviderMax)+ .describe(+ "Connector provider id: a native provider such as 'github', or 'mcp:<server host>' (e.g. 'mcp:mcp.calendly.com') for a server the viewer connected in the MCP store."+ ),+ tools: zod+ .array(+ zod+ .string()+ .max(canvasesEditCreateBodyCapabilitiesOneConnectorsItemToolsItemMax)+ )+ .min(1)+ .max(canvasesEditCreateBodyCapabilitiesOneConnectorsItemToolsMax)+ .describe('Tool names the canvas may call on this provider. Read-only tools only.'),+ })+ .describe(+ 'One provider a canvas may call through ph.connectors, with the tools it may use.'+ )+ )+ .max(canvasesEditCreateBodyCapabilitiesOneConnectorsMax)+ .optional()+ .describe(+ "Third-party providers the canvas reads through ph.connectors, each with the tools it may call. Every call runs with the viewer's own connection; declaring one shows it in the promote review."+ ),+ })+ .optional()+ .describe(+ "The project's complete new capabilities, replacing the current ones in the same publish. Send it when the change needs a capability the canvas does not declare yet, for example a new ph.state scope, insight, capture event, or network origin. Copy the current capabilities from canvas-source-retrieve and change only what you need. Omit to keep the current capabilities."+ ),prompt: zod.string().optional()diff --git a/services/mcp/src/tools/generated/canvas.ts b/services/mcp/src/tools/generated/canvas.tsindex 1e0fabb282c3..d73d76cc3c03 100644--- a/services/mcp/src/tools/generated/canvas.ts+++ b/services/mcp/src/tools/generated/canvas.ts@@ -187,6 +187,9 @@ const canvasEditCreate = (): ToolBase<if (params.operations !== undefined) {body['operations'] = params.operations}+ if (params.capabilities !== undefined) {+ body['capabilities'] = params.capabilities+ }if (params.prompt !== undefined) {body['prompt'] = params.prompt}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-edit-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-edit-create.jsonindex 3aaadbcc2b48..fd4422ad9af2 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-edit-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-edit-create.json@@ -1,6 +1,103 @@{"$schema": "https://json-schema.org/draft/2020-12/schema","properties": {+ "capabilities": {+ "description": "The project's complete new capabilities, replacing the current ones in the same publish. Send it when the change needs a capability the canvas does not declare yet, for example a new ph.state scope, insight, capture event, or network origin. Copy the current capabilities from canvas-source-retrieve and change only what you need. Omit to keep the current capabilities.",+ "properties": {+ "connectors": {+ "description": "Third-party providers the canvas reads through ph.connectors, each with the tools it may call. Every call runs with the viewer's own connection; declaring one shows it in the promote review.",+ "items": {+ "description": "One provider a canvas may call through ph.connectors, with the tools it may use.",+ "properties": {+ "provider": {+ "description": "Connector provider id: a native provider such as 'github', or 'mcp:<server host>' (e.g. 'mcp:mcp.calendly.com') for a server the viewer connected in the MCP store.",+ "maxLength": 300,+ "type": "string"+ },+ "tools": {+ "description": "Tool names the canvas may call on this provider. Read-only tools only.",+ "items": {+ "maxLength": 200,+ "type": "string"+ },+ "maxItems": 64,+ "minItems": 1,+ "type": "array"+ }+ },+ "required": ["provider", "tools"],+ "type": "object"+ },+ "maxItems": 20,+ "type": "array"+ },+ "network": {+ "properties": {+ "origins": {+ "items": {+ "format": "uri",+ "maxLength": 2048,+ "type": "string"+ },+ "maxItems": 20,+ "type": "array"+ }+ },+ "required": ["origins"],+ "type": "object"+ },+ "posthog": {+ "properties": {+ "actions": {+ "description": "Registered action verbs the canvas may invoke via ph.actions (e.g. 'annotations.create', 'tasks.create'). Each executes as the viewer; declaring one shows it in the promote review.",+ "items": {+ "maxLength": 64,+ "type": "string"+ },+ "maxItems": 32,+ "type": "array"+ },+ "agentRequests": {+ "default": false,+ "type": "boolean"+ },+ "captureEvents": {+ "items": {+ "maxLength": 200,+ "type": "string"+ },+ "maxItems": 100,+ "type": "array"+ },+ "inlineQueries": {+ "type": "boolean"+ },+ "insights": {+ "items": {+ "maxLength": 128,+ "type": "string"+ },+ "maxItems": 100,+ "type": "array"+ },+ "state": {+ "description": "State scopes the canvas may use via ph.state: 'user' (private to each viewer) and/or 'shared' (one value per canvas, team-visible).",+ "items": {+ "description": "* `user` - user\n* `shared` - shared",+ "enum": ["user", "shared"],+ "type": "string"+ },+ "maxItems": 2,+ "type": "array"+ }+ },+ "required": ["insights", "inlineQueries", "captureEvents"],+ "type": "object"+ }+ },+ "required": ["posthog", "network"],+ "type": "object"+ },"expected_current_version_id": {"anyOf": [{@@ -22,9 +119,9 @@"type": "string"},"operations": {- "description": "Edits applied in order to the canvas's current source project.",+ "description": "Edits applied in order to the canvas's current source project, all or nothing. May be empty when the edit only changes capabilities.","items": {- "description": "One per-file edit: set a file's content, or delete it.",+ "description": "One file edit: replace text in a file, write a whole file, delete it, or rename it.","properties": {"content": {"anyOf": [@@ -35,11 +132,33 @@"type": "null"}],- "description": "The file's complete new content. Null (or omitted) deletes the file."+ "description": "For 'write': the file's complete new content."+ },+ "new_path": {+ "description": "For 'rename': the file's new project-relative path.",+ "type": "string"+ },+ "new_string": {+ "description": "For 'str_replace': the text that replaces old_string. An empty string deletes old_string.",+ "type": "string"+ },+ "old_string": {+ "description": "For 'str_replace': the exact text to replace, copied from the file with a few surrounding lines so it matches one place only. If whitespace differs slightly, a unique line-by-line match is still accepted.",+ "type": "string"+ },+ "op": {+ "description": "What to do. 'str_replace' replaces old_string with new_string inside the file: the default for changing an existing file. 'write' sets the file's complete content (new files, full rewrites). 'delete' removes the file. 'rename' moves it to new_path. When omitted, it follows the fields sent: old_string or new_string means 'str_replace', new_path means 'rename', non-null content means 'write', and content null means 'delete'. An operation with none of these fields is rejected.\n\n* `write` - Write\n* `delete` - Delete\n* `rename` - Rename\n* `str_replace` - Str Replace",+ "enum": ["write", "delete", "rename", "str_replace"],+ "type": "string"},"path": {- "description": "Project-relative path of the file to write or delete (e.g. \"src/canvas.tsx\").",+ "description": "Project-relative path of the file to edit (e.g. \"src/canvas.tsx\").","type": "string"+ },+ "replace_all": {+ "default": false,+ "description": "For 'str_replace': replace every exact match of old_string instead of requiring exactly one.",+ "type": "boolean"}},"required": ["path"],@@ -52,6 +171,6 @@"type": "string"}},- "required": ["id", "operations", "expected_current_version_id"],+ "required": ["id", "expected_current_version_id"],"type": "object"}