: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): grid layout backend with patch ops and home provisioning (#83546)
Peter Kirkham89dcb036117b
diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 98516564c85b..1cb42cee8f31 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -689,6 +689,13 @@ SPECTACULAR_SETTINGS = {"CanvasStateScopeEnum": ["user", "shared"],# `kind` is a generic field name; one shared name for the canvas kind set."CanvasKindEnum": ["freeform", "grid", "component"],+ # `status`/`op`/`columns`/`schemaVersion` are generic field names; pin the grid layout sets.+ "CanvasPlacementStatusEnum": ["pending", "generating", "live", "failed"],+ "CanvasLayoutOpEnum": ["set_grid", "add_placement", "update_placement", "remove_placement"],+ # Integer choice sets need explicit (value, label) pairs; a bare list is+ # only matched for string choices.+ "CanvasGridColumnsEnum": [(4, 4), (6, 6), (8, 8), (10, 10), (12, 12)],+ "CanvasLayoutSchemaVersionEnum": [(1, 1)],# `bucket` is a generic field name; name the experiment recordings bucket set explicitly."ExperimentSessionBucketEnum": ["fired_any", "no_metric_activity", "funnel_dropoff"],# `strength` and `kind` are generic enough that the next one added anywhere would collide,diff --git a/products/canvas/backend/build_service.py b/products/canvas/backend/build_service.pyindex 48d7aa643d26..dafc0e280b77 100644--- a/products/canvas/backend/build_service.py+++ b/products/canvas/backend/build_service.py@@ -510,6 +510,68 @@ def publish_source_project(return canvas, version, build, first_publish+def publish_grid_layout(+ canvas: Canvas,+ *,+ layout: dict[str, Any],+ prompt: str | None,+ has_expected_version: bool,+ expected_version_id: str | None,+ task_id: UUID | None,+ created_by: User | None,+ was_impersonated: bool = False,+) -> tuple[Canvas, CanvasSourceVersion]:+ """Publish a validated layout document as a grid canvas's new head version.++ Same upload-then-commit versioning as file projects, but no build is+ queued and no capacity is consumed: layout is data, so the new version is+ live the moment the head advances. Raises CanvasVersionConflict or+ ObjectStorageError.+ """+ # Lock-free fail-fast, mirroring the file-project publish: reject a stale+ # publish before paying for the upload, so a doomed patch does not leave an+ # orphaned, unreferenced source object behind. Conflicts are routine on this+ # path (an agent filling a box and a user dragging widgets guard against each+ # other), so this is the common case, not a rare race. The commit transaction+ # re-checks authoritatively under the head lock in _claim_canvas_head.+ if has_expected_version:+ with team_scope(canvas.team_id):+ current = Canvas.objects.for_team(canvas.team_id).only("current_source_version_id").get(pk=canvas.pk)+ current_id = str(current.current_source_version_id) if current.current_source_version_id else None+ expected = str(expected_version_id) if expected_version_id else None+ if current_id != expected:+ raise CanvasVersionConflict(current_id)+ key, digest, size = upload_source_project(canvas.team_id, canvas.id, layout)+ with transaction.atomic(), team_scope(canvas.team_id):+ canvas = _claim_canvas_head(+ canvas,+ has_expected_version=has_expected_version,+ expected_version_id=expected_version_id,+ check_capacity=False,+ )+ version = CanvasSourceVersion.objects.create(+ team_id=canvas.team_id,+ canvas=canvas,+ parent_version_id=canvas.current_source_version_id,+ source_hash=digest,+ source_object_key=key,+ source_size=size,+ task_id=task_id,+ prompt=prompt or None,+ created_by=created_by,+ )+ canvas.current_source_version = version+ canvas.save(update_fields=["current_source_version", "updated_at"])+ _log_canvas_activity(+ canvas,+ user=created_by,+ was_impersonated=was_impersonated,+ activity="published",+ detail=Detail(name=canvas.name),+ )+ return canvas, version++def publish_current_source_version(canvas: Canvas,expected_current_version_id: str | UUID,diff --git a/products/canvas/backend/facade/__init__.py b/products/canvas/backend/facade/__init__.pynew file mode 100644index 000000000000..8b137891791f--- /dev/null+++ b/products/canvas/backend/facade/__init__.py@@ -0,0 +1 @@+diff --git a/products/canvas/backend/facade/api.py b/products/canvas/backend/facade/api.pynew file mode 100644index 000000000000..ba230bb2c86a--- /dev/null+++ b/products/canvas/backend/facade/api.py@@ -0,0 +1,12 @@+from products.canvas.backend.layout import (+ CANVAS_LAYOUT_SCHEMA_VERSION as CANVAS_LAYOUT_SCHEMA_VERSION,+ MAX_LAYOUT_PATCH_OPERATIONS as MAX_LAYOUT_PATCH_OPERATIONS,+ PLACEMENT_ID_RE as PLACEMENT_ID_RE,+ PLACEMENT_STATUSES as PLACEMENT_STATUSES,+ apply_layout_ops as apply_layout_ops,+ default_layout as default_layout,+ subtract_preexisting_diagnostics as subtract_preexisting_diagnostics,+ validate_layout as validate_layout,+ validate_layout_references as validate_layout_references,+)+from products.canvas.backend.welcome import seed_home_canvas as seed_home_canvasdiff --git a/products/canvas/backend/layout.py b/products/canvas/backend/layout.pynew file mode 100644index 000000000000..af63f16d3d04--- /dev/null+++ b/products/canvas/backend/layout.py@@ -0,0 +1,516 @@+"""Grid canvas layout validation and patch operations.++A grid canvas's "source" is a layout document — a grid definition plus+placements referencing component canvases — versioned through the same+append-only ``CanvasSourceVersion`` machinery as file projects, but never+built: layout is data, so publishing one is a metadata write.++The pure validators here mirror ``source.py``'s posture (no ORM, structured+diagnostics). Reference checks that need the database (component existence,+visibility, config-vs-schema) live in ``validate_layout_references``.+"""++import re+import json+from collections import Counter+from typing import Any, TypeGuard+from uuid import UUID++import jsonschema++from posthog.dataclasses import frozen+from posthog.models.scoping import team_scope++from products.canvas.backend.contract import GRID_COLUMN_CHOICES, MAX_COMPONENT_HEIGHT, contract_limits+from products.canvas.backend.source import diagnostic++CANVAS_LAYOUT_SCHEMA_VERSION = 1++PLACEMENT_STATUSES = ("pending", "generating", "live", "failed")+PLACEMENT_ID_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$")++MIN_ROW_HEIGHT = 24+MAX_ROW_HEIGHT = 400+MAX_GAP = 48+# Rows a layout may extend to; bounds y so a placement cannot claim an+# effectively unbounded scroll area.+MAX_GRID_ROWS = 400+# A legitimate patch edits a layout bounded by maxGridPlacements, so rewriting+# every placement plus the grid stays well inside this. The cap exists because a+# patch's transient placements never show up in the published document, so the+# document's own limits cannot bound the work an operation set costs.+MAX_LAYOUT_PATCH_OPERATIONS = 64+# Serialized ceiling for a persisted layout. Placement configs are free-form, so+# without this a grid publish (which consumes no build capacity) is an unbounded+# append-only write into object storage.+MAX_LAYOUT_BYTES = 256 * 1024++DEFAULT_LAYOUT: dict[str, Any] = {+ "schemaVersion": CANVAS_LAYOUT_SCHEMA_VERSION,+ "grid": {"columns": 6, "rowHeight": 96, "gap": 8},+ "placements": [],+}+++def default_layout() -> dict[str, Any]:+ return {+ **DEFAULT_LAYOUT,+ "grid": dict(DEFAULT_LAYOUT["grid"]),+ "placements": [],+ }+++def _validate_grid(grid: Any) -> list[dict[str, Any]]:+ if not isinstance(grid, dict):+ return [diagnostic("error", "invalid_grid", "layout.grid must be an object with columns, rowHeight, and gap")]+ diagnostics: list[dict[str, Any]] = []+ if grid.get("columns") not in GRID_COLUMN_CHOICES:+ diagnostics.append(+ diagnostic(+ "error",+ "invalid_grid",+ "layout.grid.columns must be one of " + ", ".join(str(choice) for choice in GRID_COLUMN_CHOICES),+ )+ )+ row_height = grid.get("rowHeight")+ if not _is_int(row_height) or not MIN_ROW_HEIGHT <= row_height <= MAX_ROW_HEIGHT:+ diagnostics.append(+ diagnostic(+ "error",+ "invalid_grid",+ f"layout.grid.rowHeight must be an integer between {MIN_ROW_HEIGHT} and {MAX_ROW_HEIGHT} pixels",+ )+ )+ gap = grid.get("gap")+ if not _is_int(gap) or not 0 <= gap <= MAX_GAP:+ diagnostics.append(+ diagnostic("error", "invalid_grid", f"layout.grid.gap must be an integer between 0 and {MAX_GAP} pixels")+ )+ return diagnostics+++def _is_int(value: Any) -> TypeGuard[int]:+ return isinstance(value, int) and not isinstance(value, bool)+++def _is_uuid(value: Any) -> bool:+ if not isinstance(value, str):+ return False+ try:+ UUID(value)+ except ValueError:+ return False+ return True+++def _placement_label(placement: Any, index: int) -> str:+ """Name a placement by index and, when it has a usable one, by id.++ The index shifts as placements come and go, so the id is what makes two+ placements with the same field error distinguishable — which is what keeps+ ``subtract_preexisting_diagnostics`` from cancelling one against the other.+ """+ identifier = placement.get("id") if isinstance(placement, dict) else None+ if isinstance(identifier, str) and PLACEMENT_ID_RE.match(identifier):+ return f'layout.placements[{index}] ("{identifier}")'+ return f"layout.placements[{index}]"+++def _validate_placement(placement: Any, index: int, columns: int) -> list[dict[str, Any]]:+ label = _placement_label(placement, index)+ if not isinstance(placement, dict):+ return [diagnostic("error", "invalid_placement", f"{label} must be an object")]+ diagnostics: list[dict[str, Any]] = []++ identifier = placement.get("id")+ if not isinstance(identifier, str) or not PLACEMENT_ID_RE.match(identifier):+ diagnostics.append(+ diagnostic(+ "error",+ "invalid_placement",+ f"{label}.id must be 1-64 characters of letters, digits, '_', or '-'",+ )+ )++ status = placement.get("status")+ if status not in PLACEMENT_STATUSES:+ diagnostics.append(+ diagnostic("error", "invalid_placement", f"{label}.status must be one of " + ", ".join(PLACEMENT_STATUSES))+ )++ for key, minimum, maximum in (+ ("x", 0, columns - 1),+ ("y", 0, MAX_GRID_ROWS - 1),+ ("w", 1, columns),+ ("h", 1, MAX_COMPONENT_HEIGHT),+ ):+ value = placement.get(key)+ if not _is_int(value) or not minimum <= value <= maximum:+ diagnostics.append(+ diagnostic(+ "error",+ "invalid_placement",+ f"{label}.{key} must be an integer between {minimum} and {maximum}",+ )+ )+ if _is_int(placement.get("x")) and _is_int(placement.get("w")) and placement["x"] + placement["w"] > columns:+ diagnostics.append(+ diagnostic(+ "error",+ "invalid_placement",+ f"{label} extends past the grid's {columns} columns (x + w must be <= columns)",+ )+ )++ component = placement.get("component")+ if status == "live" and not _is_uuid(component):+ diagnostics.append(+ diagnostic("error", "invalid_placement", f"{label} is live but names no component canvas id")+ )+ if component is not None and not _is_uuid(component):+ diagnostics.append(diagnostic("error", "invalid_placement", f"{label}.component must be a canvas id"))++ version = placement.get("version")+ if version is not None and version != "latest" and not _is_uuid(version):+ diagnostics.append(+ diagnostic(+ "error",+ "invalid_placement",+ f'{label}.version must be "latest" or a source version id of the component',+ )+ )++ config = placement.get("config")+ if config is not None and not isinstance(config, dict):+ diagnostics.append(diagnostic("error", "invalid_placement", f"{label}.config must be an object"))++ prompt = placement.get("prompt")+ if prompt is not None and (not isinstance(prompt, str) or len(prompt) > 10_000):+ diagnostics.append(+ diagnostic("error", "invalid_placement", f"{label}.prompt must be a string of at most 10,000 characters")+ )++ task_id = placement.get("generationTaskId")+ if task_id is not None and not _is_uuid(task_id):+ diagnostics.append(diagnostic("error", "invalid_placement", f"{label}.generationTaskId must be a task id"))++ return diagnostics+++def _overlaps(first: dict[str, Any], second: dict[str, Any]) -> bool:+ return (+ first["x"] < second["x"] + second["w"]+ and second["x"] < first["x"] + first["w"]+ and first["y"] < second["y"] + second["h"]+ and second["y"] < first["y"] + first["h"]+ )+++def validate_layout(layout: Any) -> list[dict[str, Any]]:+ """Validate a candidate layout document; pure, no ORM.++ Returns structured diagnostics; errors block publishing. Reference-level+ checks (components exist and are visible, config matches schema) are+ ``validate_layout_references``'s job.+ """+ if not isinstance(layout, dict):+ return [diagnostic("error", "invalid_layout", "the layout must be an object")]+ size = len(json.dumps(layout, separators=(",", ":"), ensure_ascii=False).encode("utf-8"))+ if size > MAX_LAYOUT_BYTES:+ return [+ diagnostic(+ "error",+ "layout_too_large",+ f"the layout is {size} bytes; a grid canvas may store at most {MAX_LAYOUT_BYTES} bytes of layout",+ )+ ]+ diagnostics: list[dict[str, Any]] = []+ if layout.get("schemaVersion") != CANVAS_LAYOUT_SCHEMA_VERSION:+ diagnostics.append(+ diagnostic("error", "unsupported_schema_version", f"schemaVersion must be {CANVAS_LAYOUT_SCHEMA_VERSION}")+ )+ diagnostics.extend(_validate_grid(layout.get("grid")))+ placements = layout.get("placements")+ if not isinstance(placements, list):+ return [*diagnostics, diagnostic("error", "invalid_layout", "layout.placements must be a list")]+ max_placements = contract_limits()["maxGridPlacements"]+ if len(placements) > max_placements:+ # Overlap detection below compares every placement against every earlier+ # one, so an over-cap document must never reach it.+ return [+ *diagnostics,+ diagnostic("error", "too_many_placements", f"a grid canvas may hold at most {max_placements} placements"),+ ]++ columns = layout.get("grid", {}).get("columns") if isinstance(layout.get("grid"), dict) else None+ effective_columns = columns if columns in GRID_COLUMN_CHOICES else max(GRID_COLUMN_CHOICES)+ seen_ids: set[str] = set()+ rects: list[dict[str, Any]] = []+ for index, placement in enumerate(placements):+ diagnostics.extend(_validate_placement(placement, index, effective_columns))+ if not isinstance(placement, dict):+ continue+ identifier = placement.get("id")+ if isinstance(identifier, str):+ if identifier in seen_ids:+ diagnostics.append(+ diagnostic("error", "duplicate_placement_id", f'placement id "{identifier}" is used twice')+ )+ seen_ids.add(identifier)+ if all(_is_int(placement.get(key)) for key in ("x", "y", "w", "h")):+ for other in rects:+ if _overlaps(placement, other):+ diagnostics.append(+ diagnostic(+ "error",+ "placements_overlap",+ f'placements "{other.get("id")}" and "{placement.get("id")}" overlap',+ )+ )+ rects.append(placement)+ return diagnostics+++def validate_layout_references(team_id: int, user_id: int | None, layout: dict[str, Any]) -> list[dict[str, Any]]:+ """Validate a layout's component references against the database.++ Only components the acting user may see (channel visibility applied) are+ placeable — a placement referencing anything else is rejected identically+ whether the component is missing, deleted, the wrong kind, or merely+ invisible, so the error does not disclose which.+ """+ from products.canvas.backend.models import ( # noqa: PLC0415 — keeps this module import-light for the pure validators+ Canvas,+ CanvasBuild,+ CanvasSourceVersion,+ )+ from products.tasks.backend.facade import api as tasks_facade # noqa: PLC0415 — same reason++ diagnostics: list[dict[str, Any]] = []+ referenced = [+ placement+ for placement in layout.get("placements", [])+ if isinstance(placement, dict) and _is_uuid(placement.get("component"))+ ]+ if not referenced:+ return diagnostics++ with team_scope(team_id):+ component_ids = {str(placement["component"]) for placement in referenced}+ components = {+ str(canvas.id): canvas+ for canvas in Canvas.objects.for_team(team_id)+ .filter(id__in=component_ids, kind=Canvas.KIND_COMPONENT, deleted=False)+ .filter(tasks_facade.visible_channels_q(user_id, relation="channel"))+ .select_related("current_source_version")+ }+ version_ids = {str(placement["version"]) for placement in referenced if _is_uuid(placement.get("version"))}+ # A pinned placement renders that version's artifact against that+ # version's contract, so both have to be read per version; the+ # component's head answers only for "latest" placements.+ pinned_versions = (+ {+ (str(version.canvas_id), str(version.id)): version+ for version in CanvasSourceVersion.objects.for_team(team_id).filter(id__in=version_ids, draft=False)+ }+ if version_ids+ else {}+ )+ renderable_versions = (+ set(+ CanvasBuild.objects.for_team(team_id)+ .filter(+ source_version_id__in=[version.id for version in pinned_versions.values()],+ status=CanvasBuild.STATUS_READY,+ artifact_object_prefix__isnull=False,+ )+ .values_list("source_version_id", flat=True)+ )+ if pinned_versions+ else set()+ )++ for placement in referenced:+ label = f'placement "{placement.get("id")}"'+ component_id = str(placement["component"])+ component = components.get(component_id)+ if component is None:+ diagnostics.append(+ diagnostic("error", "component_not_found", f"{label} references a component that is not available")+ )+ continue+ version = placement.get("version")+ pinned = pinned_versions.get((component_id, str(version))) if _is_uuid(version) else None+ if _is_uuid(version) and pinned is None:+ diagnostics.append(+ diagnostic(+ "error",+ "component_version_not_found",+ f"{label} pins a version that is not one of the component's published versions",+ )+ )+ continue+ source_version = pinned or component.current_source_version+ meta = source_version.component_meta if source_version else None+ if not isinstance(meta, dict):+ diagnostics.append(+ diagnostic(+ "error",+ "component_not_published",+ f"{label} references a component that has never published a placement contract",+ )+ )+ continue+ # A live placement renders a built artifact; without a ready build there+ # is nothing to render, so going live must wait for it. A pin is asked+ # about its own build, whose artifact may since have aged out.+ if placement.get("status") == "live":+ if pinned is not None and pinned.id not in renderable_versions:+ diagnostics.append(+ diagnostic(+ "error",+ "component_build_not_ready",+ f"{label} cannot go live: the version it pins has no build to render. "+ "Pin a version whose build is still retained, or follow the latest one.",+ )+ )+ elif pinned is None and component.published_build_id is None:+ diagnostics.append(+ diagnostic(+ "error",+ "component_build_not_ready",+ f"{label} cannot go live: the component has no ready build yet. Wait for its build to finish.",+ )+ )+ size = meta.get("size") or {}+ for axis in ("W", "H"):+ value = placement.get(axis.lower())+ if not _is_int(value):+ continue+ minimum = size.get(f"min{axis}", 1)+ maximum = size.get(f"max{axis}")+ if value < minimum or (maximum is not None and value > maximum):+ cap = f"-{maximum}" if maximum is not None else "+"+ # Advisory only: the user sizes their own grid, and components+ # are responsible for rendering responsively at any box size.+ # The contract's range still informs defaults and this hint.+ diagnostics.append(+ diagnostic(+ "warning",+ "placement_size_out_of_contract",+ f"{label} is {value} {axis.lower()} units; the component suggests {minimum}{cap}",+ )+ )+ schema = meta.get("configSchema")+ if schema is not None:+ # An omitted config is an empty config: a schema that marks fields+ # required must reject a placement that supplies none, matching how+ # it already rejects an explicit empty object.+ try:+ jsonschema.validate(placement.get("config") or {}, schema)+ except jsonschema.ValidationError as error:+ diagnostics.append(+ diagnostic(+ "error",+ "placement_config_invalid",+ f"{label} config does not match the component's schema: {error.message}",+ )+ )+ return diagnostics+++# Placement index labels shift when placements are removed; normalize them so+# a pre-existing diagnostic still matches after unrelated edits.+_PLACEMENT_INDEX_RE = re.compile(r"placements\[\d+\]")+++@frozen+class _DiagnosticKey:+ severity: str+ code: str+ message: str+++def _diagnostic_key(diag: dict[str, Any]) -> _DiagnosticKey:+ return _DiagnosticKey(+ severity=str(diag.get("severity", "")),+ code=str(diag.get("code", "")),+ message=_PLACEMENT_INDEX_RE.sub("placements[]", str(diag.get("message", ""))),+ )+++def subtract_preexisting_diagnostics(+ candidate: list[dict[str, Any]], baseline: list[dict[str, Any]]+) -> list[dict[str, Any]]:+ """Drop candidate diagnostics already present in the baseline layout.++ A patch is judged on what it changes: problems the canvas already had (a+ component deleted or republished with a stricter contract after being+ placed) must not block unrelated edits, or one rotten placement freezes+ the whole canvas.+ """+ remaining = Counter(_diagnostic_key(diag) for diag in baseline)+ fresh: list[dict[str, Any]] = []+ for diag in candidate:+ key = _diagnostic_key(diag)+ if remaining[key] > 0:+ remaining[key] -= 1+ continue+ fresh.append(diag)+ return fresh+++def apply_layout_ops(+ layout: dict[str, Any], operations: list[dict[str, Any]]+) -> tuple[dict[str, Any], list[dict[str, Any]]]:+ """Apply surgical operations to a layout document.++ Returns the edited layout (input untouched) and diagnostics; any+ diagnostic means the operation set could not be applied atomically.+ Validation of the result is the caller's job.+ """+ layout = {**layout, "placements": [dict(placement) for placement in layout.get("placements", [])]}+ diagnostics: list[dict[str, Any]] = []+ max_placements = contract_limits()["maxGridPlacements"]+ by_id = {placement.get("id"): placement for placement in layout["placements"]}+ for operation in operations:+ op = operation["op"]+ if op == "set_grid":+ layout["grid"] = operation.get("grid")+ elif op == "add_placement":+ placement = operation.get("placement") or {}+ identifier = placement.get("id")+ if identifier in by_id:+ diagnostics.append(+ diagnostic("error", "edit_target_conflict", f'a placement with id "{identifier}" already exists')+ )+ continue+ if len(layout["placements"]) >= max_placements:+ # Bound the intermediate document too: an operation set that adds+ # and removes its way past the cap costs the same work as an+ # over-cap publish while ending inside the limit.+ diagnostics.append(+ diagnostic(+ "error",+ "too_many_placements",+ f"a grid canvas may hold at most {max_placements} placements",+ )+ )+ break+ layout["placements"].append(dict(placement))+ by_id[identifier] = layout["placements"][-1]+ elif op in ("update_placement", "remove_placement"):+ identifier = operation.get("id")+ existing = by_id.get(identifier)+ if existing is None:+ diagnostics.append(+ diagnostic("error", "edit_target_missing", f'the layout has no placement with id "{identifier}"')+ )+ continue+ if op == "remove_placement":+ layout["placements"].remove(existing)+ del by_id[identifier]+ else:+ update = {key: value for key, value in (operation.get("changes") or {}).items() if key != "id"}+ existing.update(update)+ return layout, diagnosticsdiff --git a/products/canvas/backend/presentation/serializers.py b/products/canvas/backend/presentation/serializers.pyindex a8db7b437a6f..a09a66edca78 100644--- a/products/canvas/backend/presentation/serializers.py+++ b/products/canvas/backend/presentation/serializers.py@@ -8,11 +8,18 @@ from rest_framework import serializersfrom posthog.api.shared import UserBasicSerializerfrom products.canvas.backend.contract import (+ GRID_COLUMN_CHOICES,MAX_COMPONENT_HEIGHT,MAX_COMPONENT_WIDTH,canvas_sdk_version,contract_limits,)+from products.canvas.backend.facade.api import (+ CANVAS_LAYOUT_SCHEMA_VERSION,+ MAX_LAYOUT_PATCH_OPERATIONS,+ PLACEMENT_ID_RE,+ PLACEMENT_STATUSES,+)from products.canvas.backend.models import Canvas, CanvasState# Base64 expands 3 source bytes into 4 characters (padded); size the asset field@@ -326,6 +333,179 @@ class CanvasSourceProjectSerializer(serializers.Serializer):)+class CanvasGridSerializer(serializers.Serializer):+ """The grid a grid canvas lays its placements out on."""++ columns = serializers.ChoiceField(+ choices=list(GRID_COLUMN_CHOICES), help_text="Grid width in columns. One of 4, 6, 8, 10, or 12."+ )+ rowHeight = serializers.IntegerField(min_value=24, max_value=400, help_text="Height of one grid row, in pixels.")+ gap = serializers.IntegerField(min_value=0, max_value=48, help_text="Gap between placements, in pixels.")+++class CanvasPlacementSerializer(serializers.Serializer):+ """One placed widget on a grid canvas."""++ id = serializers.RegexField(+ PLACEMENT_ID_RE,+ max_length=64,+ help_text="Stable placement id, unique within the layout. 1-64 characters of letters, digits, '_', or '-'.",+ )+ status = serializers.ChoiceField(+ choices=list(PLACEMENT_STATUSES),+ help_text=(+ "Placement lifecycle: 'pending' (box drawn, no prompt yet), 'generating' (an agent task is filling it), "+ "'live' (renders its component), 'failed' (generation failed; re-prompt or remove)."+ ),+ )+ component = serializers.CharField(+ required=False,+ allow_null=True,+ help_text="Id of the component canvas this placement renders. Required once the placement is live.",+ )+ version = serializers.CharField(+ required=False,+ allow_null=True,+ help_text=(+ 'Component version to render: "latest" (the default — follows the component\'s published build) '+ "or a pinned source version id."+ ),+ )+ x = serializers.IntegerField(min_value=0, help_text="Left edge, in grid columns (0-based).")+ y = serializers.IntegerField(min_value=0, help_text="Top edge, in grid rows (0-based).")+ w = serializers.IntegerField(min_value=1, help_text="Width, in grid columns.")+ h = serializers.IntegerField(min_value=1, help_text="Height, in grid rows.")+ config = serializers.DictField(+ required=False,+ allow_null=True,+ help_text="Per-placement settings, validated against the component's configSchema.",+ )+ prompt = serializers.CharField(+ required=False,+ allow_null=True,+ max_length=10_000,+ trim_whitespace=False,+ help_text="For pending/generating/failed placements: what the user asked this box to become.",+ )+ generationTaskId = serializers.CharField(+ required=False,+ allow_null=True,+ help_text="Id of the agent task currently filling this placement, when one is running.",+ )+++class CanvasLayoutSerializer(serializers.Serializer):+ """A grid canvas's layout document — its entire 'source'."""++ schemaVersion = serializers.ChoiceField(+ choices=[CANVAS_LAYOUT_SCHEMA_VERSION],+ help_text=f"Layout schema version. Currently always {CANVAS_LAYOUT_SCHEMA_VERSION}.",+ )+ grid = CanvasGridSerializer(help_text="The grid placements are laid out on.")+ placements = CanvasPlacementSerializer(+ many=True,+ # drf-stubs types many=True against the child serializer and misses ListSerializer's max_length+ max_length=contract_limits()["maxGridPlacements"], # type: ignore[call-arg]+ # drf-spectacular drops a nested list serializer's max_length, so the+ # limit only reaches generated clients and MCP tools through the text.+ help_text=(+ "The placed widgets, at most "+ f"{contract_limits()['maxGridPlacements']}. Placements may not overlap or extend past the grid."+ ),+ )+++class CanvasLayoutPublishSerializer(serializers.Serializer):+ """Payload for publishing a complete layout document."""++ layout = CanvasLayoutSerializer(help_text="The complete layout document to publish.")+ prompt = serializers.CharField(+ required=False,+ allow_blank=True,+ trim_whitespace=False,+ help_text="Short description of the change, stored on the appended version history entry.",+ )+ expected_current_version_id = serializers.CharField(+ required=False,+ allow_null=True,+ allow_blank=False,+ help_text=(+ "Optimistic-concurrency guard: the current_version_id the layout was based on (null when the "+ "canvas has no versions yet). A moved head is rejected with 409 version_conflict. "+ "Omit to publish unguarded."+ ),+ )+++class CanvasPlacementChangesSerializer(CanvasPlacementSerializer):+ """Fields to merge into an existing placement (all optional; id cannot change)."""++ id = None # type: ignore[assignment]++ def __init__(self, *args: Any, **kwargs: Any) -> None:+ super().__init__(*args, **kwargs)+ for field in self.fields.values():+ field.required = False+++class CanvasLayoutPatchOperationSerializer(serializers.Serializer):+ """One surgical layout operation."""++ op = serializers.ChoiceField(+ choices=["set_grid", "add_placement", "update_placement", "remove_placement"],+ help_text="The operation to apply.",+ )+ grid = CanvasGridSerializer(required=False, help_text="For set_grid: the new grid definition.")+ placement = CanvasPlacementSerializer(required=False, help_text="For add_placement: the placement to add.")+ id = serializers.CharField(+ required=False, max_length=64, help_text="For update_placement/remove_placement: the target placement id."+ )+ changes = CanvasPlacementChangesSerializer(+ required=False, help_text="For update_placement: the fields to merge into the placement."+ )++ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:+ op = attrs["op"]+ required_by_op = {+ "set_grid": ["grid"],+ "add_placement": ["placement"],+ "update_placement": ["id", "changes"],+ "remove_placement": ["id"],+ }+ missing = [field for field in required_by_op[op] if field not in attrs]+ if missing:+ raise serializers.ValidationError(f"{op} requires: {', '.join(missing)}")+ return attrs+++class CanvasLayoutPatchSerializer(serializers.Serializer):+ """Payload for applying surgical operations to the canvas's current layout."""++ operations = CanvasLayoutPatchOperationSerializer(+ many=True,+ allow_empty=False,+ # drf-stubs types many=True against the child serializer and misses ListSerializer's max_length+ max_length=MAX_LAYOUT_PATCH_OPERATIONS, # type: ignore[call-arg]+ help_text=(+ f"Operations applied in order to the canvas's current layout, at most {MAX_LAYOUT_PATCH_OPERATIONS}."+ ),+ )+ prompt = serializers.CharField(+ required=False,+ allow_blank=True,+ trim_whitespace=False,+ help_text="Short description of the change, stored on the appended version history entry.",+ )+ expected_current_version_id = serializers.CharField(+ allow_null=True,+ help_text=(+ "Required optimistic-concurrency guard: the current_version_id the operations are based on "+ "(null when the canvas has no layout versions yet). A moved head is rejected with 409 "+ "version_conflict — patches cannot apply unguarded."+ ),+ )++class CanvasDiagnosticSerializer(serializers.Serializer):"""One structured validation/build diagnostic for a canvas source project."""@@ -370,6 +550,30 @@ class CanvasSummarySerializer(serializers.Serializer):return canvas_url(canvas)+class CanvasLayoutResponseSerializer(serializers.Serializer):+ """A grid canvas's layout plus the version pointer edits must be based on."""++ canvas = CanvasSummarySerializer(help_text="Identity and version pointers for the canvas.")+ layout = CanvasLayoutSerializer(+ help_text="The layout document. A grid canvas with no versions yet returns the default empty layout."+ )+ current_version_id = serializers.CharField(+ allow_null=True,+ help_text=(+ "The live layout version this document reflects — pass as expected_current_version_id when "+ "publishing or patching. Null before the first layout publish."+ ),+ )+++class CanvasLayoutPublishResponseSerializer(serializers.Serializer):+ """Result of a successful layout publish or patch. The new version is live immediately — no build runs."""++ canvas = CanvasSummarySerializer(help_text="The canvas after the publish, including the new version pointer.")+ layout = CanvasLayoutSerializer(help_text="The layout document as published.")+ current_version_id = serializers.CharField(help_text="Id of the layout version this publish created.")++class CanvasVersionSerializer(serializers.Serializer):"""One entry of a canvas's source-version history (metadata only —fetch a version's files via `source?version_id=`)."""diff --git a/products/canvas/backend/presentation/views.py b/products/canvas/backend/presentation/views.pyindex f492b45aa291..3493899e54de 100644--- a/products/canvas/backend/presentation/views.py+++ b/products/canvas/backend/presentation/views.py@@ -3,10 +3,11 @@ from typing import Any, castfrom uuid import UUIDfrom django.core.exceptions import ValidationError as DjangoValidationError-from django.db import transaction+from django.db import connection, transactionfrom django.db.models import Q, QuerySetfrom django.utils import timezone+import structlogfrom drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schemafrom rest_framework import status, viewsets@@ -29,7 +30,15 @@ from products.canvas.backend import build_service, error_reportsfrom products.canvas.backend.actions import CANVAS_ACTIONS, canvas_actions_disabledfrom products.canvas.backend.capabilities import declared_actions, declared_state_scopesfrom products.canvas.backend.contract import contract_limits-from products.canvas.backend.models import Canvas, CanvasBuild, CanvasSourceVersion, CanvasState+from products.canvas.backend.facade.api import (+ apply_layout_ops,+ default_layout,+ seed_home_canvas,+ subtract_preexisting_diagnostics,+ validate_layout,+ validate_layout_references,+)+from products.canvas.backend.models import Canvas, CanvasBuild, CanvasHomePreference, CanvasSourceVersion, CanvasStatefrom products.canvas.backend.presentation.serializers import (CanvasActionInvokeSerializer,CanvasActionResultSerializer,@@ -44,6 +53,10 @@ from products.canvas.backend.presentation.serializers import (CanvasDraftSerializer,CanvasErrorReportResultSerializer,CanvasFixRequestResultSerializer,+ CanvasLayoutPatchSerializer,+ CanvasLayoutPublishResponseSerializer,+ CanvasLayoutPublishSerializer,+ CanvasLayoutResponseSerializer,CanvasPromoteSerializer,CanvasPublishConflictSerializer,CanvasPublishCurrentVersionSerializer,@@ -71,6 +84,8 @@ from products.canvas.backend.presentation.serializers import (from products.canvas.backend.source import apply_source_edits, has_errors, validate_source_projectfrom products.tasks.backend.facade import api as tasks_facade+logger = structlog.get_logger(__name__)+# The canvas's build lifecycle returns this many recent builds (the published# build is unioned in even when it has aged past the window).BUILDS_WINDOW = 20@@ -121,19 +136,34 @@ def _state_rejection() -> Response:def _grid_rejection(canvas: Canvas) -> Response | None:- """Reject file-source writes to a grid canvas, whose source is a layout document."""+ """Reject file-source reads/writes on a grid canvas, whose source is a layout document."""if canvas.kind != Canvas.KIND_GRID:return None- return Response(- {- "detail": "Grid canvases are compositions of components; edit them through the layout endpoints, "- "not source publish.",- "code": "wrong_canvas_kind",- },- status=status.HTTP_400_BAD_REQUEST,+ return _wrong_kind_response(+ "Grid canvases are compositions of components; use the layout endpoints, not file source."+ )+++def _layout_diagnostics(team_id: int, user_id: int | None, layout: dict[str, Any]) -> list[dict[str, Any]]:+ diagnostics = validate_layout(layout)+ if has_errors(diagnostics):+ return diagnostics+ return [*diagnostics, *validate_layout_references(team_id, user_id, layout)]+++def _non_grid_rejection(canvas: Canvas) -> Response | None:+ """Reject layout reads/writes on canvases whose source is a file project."""+ if canvas.kind == Canvas.KIND_GRID:+ return None+ return _wrong_kind_response(+ "Only grid canvases have a layout; freeform and component canvases publish source projects.")+def _wrong_kind_response(detail: str) -> Response:+ return Response({"detail": detail, "code": "wrong_canvas_kind"}, status=status.HTTP_400_BAD_REQUEST)++class CanvasStateWriteThrottle(SimpleRateThrottle):"""Per viewer per canvas. State writes are interaction-driven app data, sothe ceiling is generous — it exists to stop a canvas render loop from@@ -168,7 +198,17 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):queryset = Canvas.objects.unscoped().select_related("created_by", "current_source_version")serializer_class = CanvasSerializerhttp_method_names = ["get", "post", "patch", "delete", "head", "options"]- scope_object_read_actions = ["list", "retrieve", "source", "versions", "drafts", "builds", "validate", "state"]+ scope_object_read_actions = [+ "list",+ "retrieve",+ "source",+ "versions",+ "drafts",+ "builds",+ "validate",+ "state",+ "layout",+ ]scope_object_write_actions = ["create","partial_update",@@ -185,6 +225,9 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):"set_state","invoke_action","request_agent",+ "publish_layout",+ "patch_layout",+ "home",]def get_throttles(self) -> list[BaseThrottle]:@@ -217,6 +260,8 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):"promote","revert","build_action",+ "publish_layout",+ "patch_layout",}@extend_schema(@@ -427,6 +472,9 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):`?version_id=` reads a historical version instead of the head."""canvas = self.get_object()+ rejection = _grid_rejection(canvas)+ if rejection is not None:+ return rejectionrequested_version_id = request.query_params.get("version_id")try:if requested_version_id:@@ -933,6 +981,315 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):}return Response(response)+ @extend_schema(+ operation_id="canvases_layout_retrieve",+ responses={+ 200: CanvasLayoutResponseSerializer,+ 400: OpenApiResponse(description="The canvas is not a grid canvas."),+ },+ request=None,+ parameters=[+ OpenApiParameter(+ name="version_id",+ type=str,+ required=False,+ description="Read this historical layout version instead of the head (for version browsing).",+ )+ ],+ )+ @action(methods=["GET"], detail=True)+ def layout(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """Read a grid canvas's layout document and its `current_version_id`.++ Always call this before editing: pass the returned version id as+ `expected_current_version_id` on publish/patch so concurrent edits are+ not overwritten. A grid canvas with no versions yet returns the+ default empty layout with a null version id.+ """+ canvas = self.get_object()+ rejection = _non_grid_rejection(canvas)+ if rejection is not None:+ return rejection+ requested_version_id = request.query_params.get("version_id")+ try:+ if requested_version_id:+ version = (+ CanvasSourceVersion.objects.for_team(self.team_id)+ .filter(pk=requested_version_id, canvas_id=canvas.id)+ .first()+ )+ if version is None:+ return Response({"detail": "Version not found for this canvas."}, status=status.HTTP_404_NOT_FOUND)+ layout = build_service.read_source_project(version)+ else:+ layout = self._read_current_layout(canvas)+ except DjangoValidationError:+ return Response({"detail": "Version not found for this canvas."}, status=status.HTTP_404_NOT_FOUND)+ except ObjectStorageError:+ return Response(+ {"detail": "The canvas's layout is temporarily unavailable."},+ status=status.HTTP_503_SERVICE_UNAVAILABLE,+ )+ return Response(+ CanvasLayoutResponseSerializer(+ instance={+ "canvas": canvas,+ "layout": layout,+ "current_version_id": (+ str(canvas.current_source_version_id) if canvas.current_source_version_id else None+ ),+ }+ ).data+ )++ @extend_schema(+ operation_id="canvases_layout_publish_create",+ request=CanvasLayoutPublishSerializer,+ responses={+ 200: CanvasLayoutPublishResponseSerializer,+ 400: OpenApiResponse(+ response=CanvasSourceInvalidSerializer,+ description="The canvas is not a grid canvas, or the layout failed validation.",+ ),+ 409: OpenApiResponse(+ response=CanvasPublishConflictSerializer,+ description="The canvas moved past expected_current_version_id.",+ ),+ },+ )+ @action(methods=["POST"], detail=True, url_path="layout/publish")+ def publish_layout(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """Publish a complete layout document as the grid canvas's new head version.++ Layout is data, not code: the new version is live immediately, with no+ build. Validation errors reject the publish (400) and leave the canvas+ untouched; a stale `expected_current_version_id` is rejected with 409.+ """+ canvas = self.get_object()+ rejection = _non_grid_rejection(canvas)+ if rejection is not None:+ return rejection+ payload = CanvasLayoutPublishSerializer(data=request.data)+ payload.is_valid(raise_exception=True)+ return self._publish_layout(+ request,+ canvas,+ layout=payload.validated_data["layout"],+ prompt=payload.validated_data.get("prompt"),+ has_expected_version="expected_current_version_id" in payload.validated_data,+ expected_version_id=payload.validated_data.get("expected_current_version_id"),+ )++ @extend_schema(+ operation_id="canvases_layout_patch_create",+ request=CanvasLayoutPatchSerializer,+ responses={+ 200: CanvasLayoutPublishResponseSerializer,+ 400: OpenApiResponse(+ response=CanvasSourceInvalidSerializer,+ description="An operation targeted a missing placement, or the edited layout failed validation.",+ ),+ 409: OpenApiResponse(+ response=CanvasPublishConflictSerializer,+ description="The canvas moved past expected_current_version_id.",+ ),+ },+ )+ @action(methods=["POST"], detail=True, url_path="layout/patch")+ def patch_layout(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """Apply surgical operations to the grid canvas's current layout.++ The default write path for both the editor and agents: add, move,+ resize, fill, or remove one placement without resending the layout.+ `expected_current_version_id` is mandatory so an agent filling a box+ and a user rearranging widgets cannot overwrite each other.+ """+ canvas = self.get_object()+ rejection = _non_grid_rejection(canvas)+ if rejection is not None:+ return rejection+ payload = CanvasLayoutPatchSerializer(data=request.data)+ payload.is_valid(raise_exception=True)+ try:+ current = self._read_current_layout(canvas)+ except ObjectStorageError:+ return Response(+ {"detail": "The canvas's layout is temporarily unavailable."},+ status=status.HTTP_503_SERVICE_UNAVAILABLE,+ )+ layout, diagnostics = apply_layout_ops(current, payload.validated_data["operations"])+ if diagnostics:+ return Response(+ {+ "detail": "The operations could not be applied to the canvas's current layout.",+ "code": "invalid_layout",+ "diagnostics": diagnostics,+ },+ status=status.HTTP_400_BAD_REQUEST,+ )+ return self._publish_layout(+ request,+ canvas,+ layout=layout,+ prompt=payload.validated_data.get("prompt"),+ has_expected_version=True,+ expected_version_id=payload.validated_data["expected_current_version_id"],+ baseline_layout=current,+ )++ def _publish_layout(+ self,+ request: Request,+ canvas: Canvas,+ *,+ layout: dict[str, Any],+ prompt: str | None,+ has_expected_version: bool,+ expected_version_id: str | None,+ baseline_layout: dict[str, Any] | None = None,+ ) -> Response:+ acting_user = self._request_user()+ acting_user_id = acting_user.id if acting_user else None+ diagnostics = _layout_diagnostics(self.team_id, acting_user_id, layout)+ # Patches (which pass their baseline) answer only for the problems they+ # introduce; publishes replace the whole document and stay strict.+ if baseline_layout is not None and has_errors(diagnostics):+ diagnostics = subtract_preexisting_diagnostics(+ diagnostics, _layout_diagnostics(self.team_id, acting_user_id, baseline_layout)+ )+ if has_errors(diagnostics):+ return Response(+ {+ "detail": "The layout failed validation; fix the error diagnostics and publish again.",+ "code": "invalid_layout",+ "diagnostics": diagnostics,+ },+ status=status.HTTP_400_BAD_REQUEST,+ )+ user = self._request_user()+ task_id = self._sandbox_task_id(request)+ try:+ canvas, version = build_service.publish_grid_layout(+ canvas,+ layout=layout,+ prompt=prompt,+ has_expected_version=has_expected_version,+ expected_version_id=expected_version_id,+ task_id=task_id,+ created_by=user,+ was_impersonated=is_impersonated(request),+ )+ except build_service.CanvasVersionConflict as conflict:+ return _conflict_response(conflict)+ except ObjectStorageError:+ return Response(+ {"detail": "Canvas source storage is temporarily unavailable; the layout was not saved."},+ status=status.HTTP_503_SERVICE_UNAVAILABLE,+ )+ self._report_canvas_action(+ "canvas layout published",+ canvas,+ version_id=str(version.id),+ placement_count=len(layout.get("placements", [])),+ is_sandbox_publish=task_id is not None,+ )+ return Response(+ CanvasLayoutPublishResponseSerializer(+ instance={"canvas": canvas, "layout": layout, "current_version_id": str(version.id)}+ ).data+ )++ def _read_current_layout(self, canvas: Canvas) -> dict[str, Any]:+ """The canvas's head layout document, or the default empty layout before+ the first publish. Raises ObjectStorageError when storage is unavailable."""+ if canvas.current_source_version is None:+ return default_layout()+ return build_service.read_source_project(canvas.current_source_version)++ @extend_schema(+ operation_id="canvases_home_create",+ request=None,+ responses={+ 200: OpenApiResponse(response=CanvasSerializer, description="The caller's existing home canvas."),+ 201: OpenApiResponse(+ response=CanvasSerializer, description="A home canvas was provisioned for the caller."+ ),+ 403: OpenApiResponse(description="Home is a viewer surface; sandbox tokens cannot provision it."),+ },+ )+ @action(methods=["POST"], detail=False)+ def home(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """Get or provision the caller's home canvas.++ Idempotent: returns the user's existing home canvas, or creates a grid+ canvas in their personal channel and points their home preference at+ it. The home surface calls this on open.+ """+ user = self._request_user()+ if user is None or self._is_sandbox_authenticated(request):+ return Response(+ {"detail": "Home is a viewer surface; sandbox tokens cannot provision it."},+ status=status.HTTP_403_FORBIDDEN,+ )+ existing = self._home_canvas_for(user)+ if existing is not None:+ return Response(CanvasSerializer(existing).data)+ channel_id = tasks_facade.ensure_personal_channel_id(self.team_id, user.id)+ with transaction.atomic():+ # Serialize provisioning per user: two concurrent first-opens (two+ # tabs, or desktop plus web) would otherwise both miss the read above+ # and each create a "Home" canvas, leaving one orphaned. Re-read under+ # the lock so the loser returns the winner's canvas instead.+ self._lock_home_provisioning(user.id)+ existing = self._home_canvas_for(user)+ if existing is not None:+ return Response(CanvasSerializer(existing).data)+ canvas = Canvas.objects.create(+ team_id=self.team_id,+ channel_id=channel_id,+ name="Home",+ kind=Canvas.KIND_GRID,+ description="Your personal home canvas.",+ created_by=user,+ )+ CanvasHomePreference.objects.for_team(self.team_id).update_or_create(+ team_id=self.team_id, user=user, defaults={"canvas": canvas}+ )+ # Starter content is best-effort: an empty home still provisions when+ # object storage or the seed publish is unavailable.+ try:+ seed_home_canvas(canvas, user=user, channel_id=channel_id)+ except Exception:+ logger.exception("Failed to seed home canvas", canvas_id=str(canvas.id), team_id=self.team_id)+ self._log_canvas_activity(canvas, "created", Detail(name=canvas.name))+ self._report_canvas_action("canvas home provisioned", canvas)+ return Response(CanvasSerializer(canvas).data, status=status.HTTP_201_CREATED)++ def _lock_home_provisioning(self, user_id: int) -> None:+ """Serialize home provisioning for one user inside the current transaction.++ There is no preference row to lock before the first provision, so a+ transaction-scoped advisory lock guards the read-then-create window.+ """+ with connection.cursor() as cursor:+ cursor.execute(+ "SELECT pg_advisory_xact_lock(hashtextextended(%s, 0))",+ [f"canvas_home:{self.team_id}:{user_id}"],+ )++ def _home_canvas_for(self, user: User) -> Canvas | None:+ """The user's home canvas, or None when there is none to open.++ Deleting a canvas is a soft delete that leaves the pointer behind, so a+ pointer at a deleted canvas means "no home set", not a broken home.+ """+ preference = (+ CanvasHomePreference.objects.for_team(self.team_id).select_related("canvas").filter(user=user).first()+ )+ if preference is None or preference.canvas.deleted:+ return None+ return preference.canvas+@extend_schema(operation_id="canvases_build_action_create",request=CanvasBuildActionSerializer,diff --git a/products/canvas/backend/tests/test_grid_layout.py b/products/canvas/backend/tests/test_grid_layout.pynew file mode 100644index 000000000000..4b1cf301ca48--- /dev/null+++ b/products/canvas/backend/tests/test_grid_layout.py@@ -0,0 +1,529 @@+from typing import Any, cast++from unittest.mock import patch++from django.test import SimpleTestCase++from parameterized import parameterized+from rest_framework import status++from posthog.models.integration import Integration+from posthog.models.scoping import team_scope+from posthog.models.user import User++from products.canvas.backend import welcome+from products.canvas.backend.layout import (+ MAX_LAYOUT_PATCH_OPERATIONS,+ apply_layout_ops,+ default_layout,+ validate_layout,+)+from products.canvas.backend.models import Canvas, CanvasBuild, CanvasHomePreference, CanvasState+from products.canvas.backend.presentation.views import CanvasViewSet+from products.canvas.backend.source import has_errors, validate_source_project+from products.canvas.backend.tests.test_canvas_api import CanvasAPIBaseTest+from products.canvas.backend.tests.test_component_store import COMPONENT_META+from products.tasks.backend.models import Channel+++def layout(**overrides) -> dict[str, Any]:+ doc = default_layout()+ doc.update(overrides)+ return doc+++def placement(**overrides) -> dict[str, Any]:+ base = {"id": "p1", "status": "pending", "x": 0, "y": 0, "w": 2, "h": 1}+ base.update(overrides)+ return base+++class GridLayoutAPIBaseTest(CanvasAPIBaseTest):+ def _create_grid(self, **overrides) -> str:+ return self._create_canvas(kind="grid", name="My grid", **overrides)++ def _create_component(self, *, built: bool = True, **overrides) -> str:+ component_id = self._create_canvas(kind="component", name="Weather", **overrides)+ response = self._publish(component_id, self._project(component=COMPONENT_META))+ assert response.status_code == status.HTTP_200_OK, response.json()+ if built:+ # The build worker is mocked out, so mark the queued build ready by hand.+ with team_scope(self.team.id):+ build = CanvasBuild.objects.for_team(self.team.id).get(canvas_id=component_id)+ build.status = CanvasBuild.STATUS_READY+ build.artifact_object_prefix = f"canvas_artifact/team_{self.team.id}/{component_id}/{build.id}"+ build.save(update_fields=["status", "artifact_object_prefix"])+ Canvas.objects.for_team(self.team.id).filter(pk=component_id).update(published_build=build)+ return component_id++ def _publish_layout(self, canvas_id: str, doc: dict[str, Any] | None = None, **payload):+ return self.client.post(+ f"/api/projects/{self.team.id}/canvases/{canvas_id}/layout/publish/",+ {"layout": doc or layout(), **payload},+ format="json",+ )++ def _patch_layout(self, canvas_id: str, operations: list[dict[str, Any]], expected: str | None, **payload):+ return self.client.post(+ f"/api/projects/{self.team.id}/canvases/{canvas_id}/layout/patch/",+ {"operations": operations, "expected_current_version_id": expected, **payload},+ format="json",+ )++ def _get_layout(self, canvas_id: str):+ return self.client.get(f"/api/projects/{self.team.id}/canvases/{canvas_id}/layout/")++ def _publish_component_version(self, component_id: str, *, config_schema: dict[str, Any]) -> str:+ meta = {**COMPONENT_META, "configSchema": config_schema}+ response = self._publish(component_id, self._project(component=meta))+ assert response.status_code == status.HTTP_200_OK, response.json()+ return cast(str, response.json()["current_version_id"])++ def _mark_head_build_ready(self, component_id: str) -> None:+ with team_scope(self.team.id):+ component = Canvas.objects.for_team(self.team.id).get(pk=component_id)+ build = CanvasBuild.objects.for_team(self.team.id).get(+ source_version_id=component.current_source_version_id+ )+ build.status = CanvasBuild.STATUS_READY+ build.artifact_object_prefix = f"canvas_artifact/team_{self.team.id}/{component_id}/{build.id}"+ build.save(update_fields=["status", "artifact_object_prefix"])+ Canvas.objects.for_team(self.team.id).filter(pk=component_id).update(published_build=build)+++class TestGridLayoutApi(GridLayoutAPIBaseTest):+ def test_layout_publish_round_trips_without_queuing_a_build(self):+ grid_id = self._create_grid()+ component_id = self._create_component()+ self.enqueue.reset_mock()++ doc = layout(placements=[placement(status="live", component=component_id, config={"location": "Lisbon"})])+ response = self._publish_layout(grid_id, doc)+ assert response.status_code == status.HTTP_200_OK, response.json()+ version_id = response.json()["current_version_id"]++ read = self._get_layout(grid_id)+ assert read.status_code == status.HTTP_200_OK+ assert read.json()["layout"]["placements"][0]["component"] == component_id+ assert read.json()["current_version_id"] == version_id+ self.enqueue.assert_not_called()++ def test_unpublished_grid_returns_default_layout(self):+ grid_id = self._create_grid()+ read = self._get_layout(grid_id)+ assert read.status_code == status.HTTP_200_OK+ assert read.json()["layout"] == default_layout()+ assert read.json()["current_version_id"] is None++ def test_layout_endpoints_reject_non_grid_canvases(self):+ freeform_id = self._create_canvas()+ assert self._get_layout(freeform_id).status_code == status.HTTP_400_BAD_REQUEST+ response = self._publish_layout(freeform_id)+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json()["code"] == "wrong_canvas_kind"++ def test_source_rejects_grid_canvases(self):+ grid_id = self._create_grid()+ response = self.client.get(f"/api/projects/{self.team.id}/canvases/{grid_id}/source/")+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json()["code"] == "wrong_canvas_kind"++ def test_guarded_publish_conflict(self):+ grid_id = self._create_grid()+ first = self._publish_layout(grid_id, expected_current_version_id=None)+ assert first.status_code == status.HTTP_200_OK+ stale = self._publish_layout(grid_id, expected_current_version_id=None)+ assert stale.status_code == status.HTTP_409_CONFLICT+ assert stale.json()["current_version_id"] == first.json()["current_version_id"]++ def test_patch_flow_draw_fill_move_remove(self):+ grid_id = self._create_grid()+ component_id = self._create_component()++ drawn = self._patch_layout(+ grid_id,+ [{"op": "add_placement", "placement": placement(prompt="weather for Lisbon")}],+ expected=None,+ )+ assert drawn.status_code == status.HTTP_200_OK, drawn.json()+ version = drawn.json()["current_version_id"]++ filled = self._patch_layout(+ grid_id,+ [+ {+ "op": "update_placement",+ "id": "p1",+ "changes": {"status": "live", "component": component_id, "config": {"location": "Lisbon"}},+ }+ ],+ expected=version,+ )+ assert filled.status_code == status.HTTP_200_OK, filled.json()+ placed = filled.json()["layout"]["placements"][0]+ assert placed["status"] == "live"+ assert placed["prompt"] == "weather for Lisbon"++ moved = self._patch_layout(+ grid_id,+ [{"op": "update_placement", "id": "p1", "changes": {"x": 2, "y": 3}}],+ expected=filled.json()["current_version_id"],+ )+ assert moved.status_code == status.HTTP_200_OK++ removed = self._patch_layout(+ grid_id,+ [{"op": "remove_placement", "id": "p1"}],+ expected=moved.json()["current_version_id"],+ )+ assert removed.status_code == status.HTTP_200_OK+ assert removed.json()["layout"]["placements"] == []++ def test_patch_against_stale_version_conflicts(self):+ grid_id = self._create_grid()+ first = self._patch_layout(grid_id, [{"op": "add_placement", "placement": placement()}], expected=None)+ assert first.status_code == status.HTTP_200_OK+ stale = self._patch_layout(grid_id, [{"op": "remove_placement", "id": "p1"}], expected=None)+ assert stale.status_code == status.HTTP_409_CONFLICT++ def test_patch_unknown_placement_rejected(self):+ grid_id = self._create_grid()+ response = self._patch_layout(grid_id, [{"op": "remove_placement", "id": "ghost"}], expected=None)+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert any(entry["code"] == "edit_target_missing" for entry in response.json()["diagnostics"])++ def test_patch_not_blocked_by_preexisting_invalid_placement(self):+ grid_id = self._create_grid()+ component_id = self._create_component()+ doc = layout(placements=[placement(status="live", component=component_id, config={"location": "Lisbon"})])+ published = self._publish_layout(grid_id, doc)+ assert published.status_code == status.HTTP_200_OK, published.json()+ version_id = published.json()["current_version_id"]+ # The component disappears after placement; the live placement is now+ # invalid through no fault of the layout's own edits.+ with team_scope(self.team.id):+ Canvas.objects.for_team(self.team.id).filter(pk=component_id).update(deleted=True)++ added = self._patch_layout(+ grid_id,+ [{"op": "add_placement", "placement": placement(id="p2", x=2)}],+ expected=version_id,+ )+ assert added.status_code == status.HTTP_200_OK, added.json()++ # A patch that introduces a problem of its own is still rejected.+ worsened = self._patch_layout(+ grid_id,+ [{"op": "add_placement", "placement": placement(id="p3", x=4, status="live")}],+ expected=added.json()["current_version_id"],+ )+ assert worsened.status_code == status.HTTP_400_BAD_REQUEST+ assert any(entry["code"] == "invalid_placement" for entry in worsened.json()["diagnostics"])++ def test_live_placement_requires_available_component(self):+ grid_id = self._create_grid()+ unpublished_id = self._create_canvas(kind="component", name="Empty component")+ doc = layout(placements=[placement(status="live", component=unpublished_id)])+ response = self._publish_layout(grid_id, doc)+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert any(entry["code"] == "component_not_published" for entry in response.json()["diagnostics"])++ def test_live_placement_requires_ready_build(self):+ grid_id = self._create_grid()+ component_id = self._create_component(built=False)+ doc = layout(placements=[placement(status="live", component=component_id)])+ rejected = self._publish_layout(grid_id, doc)+ assert rejected.status_code == status.HTTP_400_BAD_REQUEST+ assert any(entry["code"] == "component_build_not_ready" for entry in rejected.json()["diagnostics"])+ # The same placement may wait in the generating state until the build is ready.+ staged = self._publish_layout(+ grid_id, layout(placements=[placement(status="generating", component=component_id)])+ )+ assert staged.status_code == status.HTTP_200_OK, staged.json()++ def test_component_in_anothers_personal_channel_is_not_placeable(self):+ with team_scope(self.team.id):+ other_personal = Channel.objects.create(+ team=self.team,+ name="them",+ channel_type=Channel.ChannelType.PERSONAL,+ created_by=None,+ )+ component = Canvas.objects.create(+ team=self.team, channel=other_personal, name="Private", kind=Canvas.KIND_COMPONENT+ )+ grid_id = self._create_grid()+ doc = layout(placements=[placement(status="live", component=str(component.id))])+ response = self._publish_layout(grid_id, doc)+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert any(entry["code"] == "component_not_found" for entry in response.json()["diagnostics"])++ def test_config_violating_component_schema_rejected(self):+ grid_id = self._create_grid()+ component_id = self._create_component()+ doc = layout(placements=[placement(status="live", component=component_id, config={"location": 5})])+ response = self._publish_layout(grid_id, doc)+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert any(entry["code"] == "placement_config_invalid" for entry in response.json()["diagnostics"])++ @parameterized.expand(+ [("publish", "layout__placements__non_field_errors"), ("patch", "operations__non_field_errors")]+ )+ def test_oversized_layout_writes_are_rejected_at_the_request_boundary(self, route: str, rejected_attr: str):+ # Per-placement and per-operation validation is itself work an attacker+ # pays nothing for, so the count has to be refused before any of it runs+ # rather than reported as a layout diagnostic afterwards.+ grid_id = self._create_grid()+ if route == "publish":+ doc = layout(placements=[placement(id=f"p{index}") for index in range(400)])+ response = self._publish_layout(grid_id, doc)+ else:+ operations = [+ {"op": "add_placement", "placement": placement(id=f"p{index}")}+ for index in range(MAX_LAYOUT_PATCH_OPERATIONS + 1)+ ]+ response = self._patch_layout(grid_id, operations, expected=None)+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert response.json()["code"] == "max_length", response.json()+ assert response.json()["attr"] == rejected_attr, response.json()++ def test_pinned_version_is_validated_against_its_own_config_schema(self):+ grid_id = self._create_grid()+ component_id = self._create_component()+ pinned_version = self._publish_component_version(+ component_id, config_schema={"type": "object", "properties": {"location": {"type": "string"}}}+ )+ # The component republishes with an incompatible contract; the pinned+ # placement still renders the version it named, so it answers to that+ # version's schema and not to the head's.+ self._publish_component_version(+ component_id,+ config_schema={"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]},+ )+ doc = layout(+ placements=[+ placement(+ status="generating",+ component=component_id,+ version=pinned_version,+ config={"location": "Lisbon"},+ )+ ]+ )+ response = self._publish_layout(grid_id, doc)+ assert response.status_code == status.HTTP_200_OK, response.json()++ def test_live_placement_pinned_to_a_version_without_a_ready_build_rejected(self):+ grid_id = self._create_grid()+ component_id = self._create_component()+ # The pinned version's own build never went ready; only the head's did,+ # which is what a placement pinned to the older version cannot render.+ pinned_version = self._publish_component_version(+ component_id, config_schema={"type": "object", "properties": {"location": {"type": "string"}}}+ )+ self._publish_component_version(+ component_id, config_schema={"type": "object", "properties": {"location": {"type": "string"}}}+ )+ self._mark_head_build_ready(component_id)++ doc = layout(placements=[placement(status="live", component=component_id, version=pinned_version)])+ response = self._publish_layout(grid_id, doc)+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert any(entry["code"] == "component_build_not_ready" for entry in response.json()["diagnostics"])++ def test_placement_pinned_to_an_unknown_version_rejected(self):+ grid_id = self._create_grid()+ component_id = self._create_component()+ doc = layout(+ placements=[+ placement(status="generating", component=component_id, version="00000000-0000-4000-8000-000000000000")+ ]+ )+ response = self._publish_layout(grid_id, doc)+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert any(entry["code"] == "component_version_not_found" for entry in response.json()["diagnostics"])++ @parameterized.expand(+ [+ ("config_omitted", None, status.HTTP_400_BAD_REQUEST),+ ("config_empty", {}, status.HTTP_400_BAD_REQUEST),+ ("config_complete", {"location": "Lisbon"}, status.HTTP_200_OK),+ ]+ )+ def test_required_config_properties_are_enforced(self, _name: str, config: dict[str, Any] | None, expected: int):+ # Omitting `config` hands the component the same empty object as+ # `config: {}`, so both must answer for the schema's required keys.+ grid_id = self._create_grid()+ component_id = self._create_component()+ self._publish_component_version(+ component_id,+ config_schema={+ "type": "object",+ "properties": {"location": {"type": "string"}},+ "required": ["location"],+ },+ )+ overrides: dict[str, Any] = {"status": "generating", "component": component_id}+ if config is not None:+ overrides["config"] = config+ response = self._publish_layout(grid_id, layout(placements=[placement(**overrides)]))+ assert response.status_code == expected, response.json()++ def test_placement_size_outside_component_contract_is_advisory(self):+ # The user sizes their own grid; a size outside the component's+ # suggested range must not block the publish.+ grid_id = self._create_grid()+ component_id = self._create_component()+ meta = {**COMPONENT_META, "size": {"defaultW": 2, "defaultH": 1, "minW": 2, "minH": 1, "maxW": 3}}+ response = self._publish(component_id, self._project(component=meta))+ assert response.status_code == status.HTTP_200_OK+ doc = layout(placements=[placement(status="live", component=component_id, w=1)])+ published = self._publish_layout(grid_id, doc)+ assert published.status_code == status.HTTP_200_OK, published.json()+++class TestHomeProvisioning(GridLayoutAPIBaseTest):+ def _home(self):+ return self.client.post(f"/api/projects/{self.team.id}/canvases/home/")++ def test_home_provisions_once_and_is_idempotent(self):+ first = self._home()+ assert first.status_code == status.HTTP_201_CREATED, first.json()+ assert first.json()["kind"] == "grid"+ second = self._home()+ assert second.status_code == status.HTTP_200_OK+ assert second.json()["id"] == first.json()["id"]+ with team_scope(self.team.id):+ assert CanvasHomePreference.objects.for_team(self.team.id).filter(user=self.user).count() == 1++ def test_home_reprovisions_after_canvas_deletion(self):+ first = self._home()+ self.client.delete(f"/api/projects/{self.team.id}/canvases/{first.json()['id']}/")+ replacement = self._home()+ assert replacement.status_code == status.HTTP_201_CREATED+ assert replacement.json()["id"] != first.json()["id"]++ @parameterized.expand([("without_github", False), ("with_github", True)])+ def test_home_seeds_welcome_checklist(self, _name: str, github_connected: bool):+ if github_connected:+ Integration.objects.create(team=self.team, kind="github", integration_id="1", config={})+ first = self._home()+ assert first.status_code == status.HTTP_201_CREATED, first.json()+ home_id = first.json()["id"]++ read = self._get_layout(home_id)+ assert read.status_code == status.HTTP_200_OK+ placements = read.json()["layout"]["placements"]+ assert len(placements) == 1+ seeded = placements[0]+ assert seeded["status"] == "live"+ assert (seeded["w"], seeded["h"]) == (2, 5)++ with team_scope(self.team.id):+ component = Canvas.objects.for_team(self.team.id).get(id=seeded["component"])+ assert component.kind == Canvas.KIND_COMPONENT+ assert component.name == welcome.WELCOME_COMPONENT_NAME+ assert component.channel_id == Canvas.objects.for_team(self.team.id).get(id=home_id).channel_id+ assert component.current_source_version is not None+ assert component.current_source_version.component_meta is not None+ state = CanvasState.objects.for_team(self.team.id).get(+ canvas=component, scope=CanvasState.SCOPE_USER, user=self.user, key=welcome.WELCOME_STATE_KEY+ )+ assert state.value == {"download-desktop": True, "connect-github": github_connected}++ def test_losing_a_provisioning_race_returns_the_winners_home(self):+ # Two first opens (two tabs, or desktop plus web) both miss the pointer.+ # The loser must hand back the winner's canvas instead of provisioning a+ # second Home that nothing points at.+ first = self._home()+ assert first.status_code == status.HTTP_201_CREATED, first.json()+ unlocked_read = CanvasViewSet._home_canvas_for+ reads = {"count": 0}++ def missed_once(view: CanvasViewSet, user: User) -> Canvas | None:+ reads["count"] += 1+ return None if reads["count"] == 1 else unlocked_read(view, user)++ with patch.object(CanvasViewSet, "_home_canvas_for", missed_once):+ raced = self._home()+ assert raced.status_code == status.HTTP_200_OK, raced.json()+ assert raced.json()["id"] == first.json()["id"]+ with team_scope(self.team.id):+ assert Canvas.objects.for_team(self.team.id).filter(kind=Canvas.KIND_GRID, deleted=False).count() == 1++ def test_home_provisions_even_when_seeding_fails(self):+ with patch(+ "products.canvas.backend.presentation.views.seed_home_canvas", side_effect=RuntimeError("storage down")+ ):+ response = self._home()+ assert response.status_code == status.HTTP_201_CREATED, response.json()+ read = self._get_layout(response.json()["id"])+ assert read.status_code == status.HTTP_200_OK+ assert read.json()["layout"]["placements"] == []+++class TestWelcomeChecklistProject(SimpleTestCase):+ def test_seed_project_passes_source_validation(self):+ diagnostics = validate_source_project(welcome.welcome_checklist_project(), kind="component")+ assert not has_errors(diagnostics), diagnostics+++class TestLayoutValidation(CanvasAPIBaseTest):+ @parameterized.expand(+ [+ ("wrong_schema_version", layout(schemaVersion=2), "unsupported_schema_version"),+ ("bad_columns", layout(grid={"columns": 5, "rowHeight": 96, "gap": 8}), "invalid_grid"),+ (+ "overlap",+ layout(placements=[placement(), placement(id="p2", x=1)]),+ "placements_overlap",+ ),+ (+ "past_grid_edge",+ layout(placements=[placement(x=5, w=2)]),+ "invalid_placement",+ ),+ (+ "duplicate_ids",+ layout(placements=[placement(), placement(y=5)]),+ "duplicate_placement_id",+ ),+ (+ "live_without_component",+ layout(placements=[placement(status="live")]),+ "invalid_placement",+ ),+ (+ "too_many_placements",+ layout(placements=[placement(id=f"p{i}", x=i % 6, y=i // 6) for i in range(25)]),+ "too_many_placements",+ ),+ ]+ )+ def test_invalid_layouts_produce_error(self, _name, doc, expected_code):+ diagnostics = validate_layout(doc)+ assert expected_code in [entry["code"] for entry in diagnostics], diagnostics++ def test_apply_ops_leaves_input_untouched(self):+ original = layout(placements=[placement()])+ edited, diagnostics = apply_layout_ops(original, [{"op": "remove_placement", "id": "p1"}])+ assert diagnostics == []+ assert edited["placements"] == []+ assert original["placements"] == [placement()]++ def test_oversized_layout_is_not_walked_for_overlaps(self):+ # Overlap detection compares every placement against every earlier one,+ # so an over-cap document must be rejected before that scan runs.+ doc = layout(placements=[placement(id=f"p{index}") for index in range(400)])+ diagnostics = validate_layout(doc)+ assert [entry["code"] for entry in diagnostics] == ["too_many_placements"]++ def test_apply_ops_rejects_growing_past_the_placement_cap(self):+ operations = [{"op": "add_placement", "placement": placement(id=f"p{index}")} for index in range(40)]+ _, diagnostics = apply_layout_ops(default_layout(), operations)+ assert any(entry["code"] == "too_many_placements" for entry in diagnostics)++ def test_layout_larger_than_the_persisted_cap_is_rejected(self):+ doc = layout(placements=[placement(config={"blob": "x" * 300_000})])+ diagnostics = validate_layout(doc)+ assert any(entry["code"] == "layout_too_large" for entry in diagnostics)diff --git a/products/canvas/backend/welcome.py b/products/canvas/backend/welcome.pynew file mode 100644index 000000000000..6892d80fc26e--- /dev/null+++ b/products/canvas/backend/welcome.py@@ -0,0 +1,264 @@+"""Starter content for a freshly provisioned home canvas.++A new home grid should not open onto an empty lattice: provisioning seeds one+"Welcome checklist" component so the first thing a new user sees is a working+widget that walks them through setup. The checklist keeps its ticks in+``ph.state`` (user scope), pre-seeded with what the account already tells us:+they are reading it inside the desktop app, and whether the team has the+GitHub integration.+"""++from typing import Any+from uuid import UUID++import structlog++from posthog.models.integration import Integration+from posthog.models.user import User++from products.canvas.backend import build_service+from products.canvas.backend.layout import default_layout+from products.canvas.backend.models import Canvas, CanvasState+from products.canvas.backend.source import synthetic_source_project++logger = structlog.get_logger(__name__)++WELCOME_COMPONENT_NAME = "Welcome checklist"+WELCOME_STATE_KEY = "checked"++_CHECKLIST_CODE = """\+import { useEffect, useState } from "react";+import {+ Button,+ Checkbox,+ Label,+ SkeletonText,+ Text,+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@posthog/quill";+import { Info } from "lucide-react";++const ITEMS = [+ {+ id: "download-desktop",+ label: "Download PostHog Desktop",+ hint: null,+ },+ {+ id: "connect-github",+ label: "Connect GitHub",+ hint: "Connect a repository in settings so agents can open pull requests for you.",+ },+ {+ id: "add-widget",+ label: "Add a widget to this canvas",+ hint: "Select Edit in the top right, then click and drag anywhere on the dotted grid and describe what should go there.",+ },+ {+ id: "create-space",+ label: "Create your first space",+ hint: "Spaces organize work with your team. Open the spaces list in the sidebar and select New space.",+ },+ {+ id: "start-task",+ label: "Start your first task",+ hint: "Open a space and tell the agent what you want done. It picks the task up and reports back.",+ },+];++// Persistence needs both the SDK surface and a host that answers it. An old+// runtime without ph.state must degrade to session-only ticks, never crash+// the tile.+const stateApi =+ typeof ph !== "undefined" && ph.state && typeof ph.state.get === "function"+ ? ph.state+ : null;++export default function WelcomeChecklist() {+ const [checked, setChecked] = useState(null);++ useEffect(() => {+ let cancelled = false;+ if (!stateApi) {+ setChecked({ "download-desktop": true });+ } else {+ stateApi+ .get("checked", { scope: "user" })+ .then((value) => {+ if (!cancelled) {+ setChecked(value && typeof value === "object" ? value : {});+ }+ })+ .catch(() => {+ if (!cancelled) {+ setChecked({});+ }+ });+ }+ return () => {+ cancelled = true;+ };+ }, []);++ const toggle = (id, value) => {+ if (!checked) {+ return;+ }+ const next = { ...checked, [id]: value };+ setChecked(next);+ if (stateApi) {+ stateApi.set("checked", next, { scope: "user" }).catch(() => {});+ }+ };++ const done = checked ? ITEMS.filter((item) => checked[item.id]).length : 0;++ return (+ <div className="flex h-full flex-col gap-2 overflow-y-auto p-3">+ <div className="flex items-baseline justify-between gap-2">+ <Text weight="medium">Welcome to PostHog</Text>+ {checked ? (+ <Text size="sm" className="text-muted-foreground">+ {done} of {ITEMS.length} done+ </Text>+ ) : null}+ </div>+ {checked === null ? (+ <SkeletonText lines={5} className="text-sm" />+ ) : (+ <div className="flex flex-col gap-1.5">+ {ITEMS.map((item) => (+ <div key={item.id} className="flex items-center gap-2">+ <Checkbox+ id={"checklist-" + item.id}+ checked={!!checked[item.id]}+ onCheckedChange={(value) => toggle(item.id, value === true)}+ />+ <Label+ htmlFor={"checklist-" + item.id}+ className={+ "text-sm" ++ (checked[item.id] ? " text-muted-foreground line-through" : "")+ }+ >+ {item.label}+ </Label>+ {item.hint ? (+ <Tooltip>+ {/* A focusable button, not a bare icon: the tooltip carries the+ only instructions for the step, so it has to be reachable+ by keyboard and have a name a screen reader can announce. */}+ <TooltipTrigger+ render={+ <Button+ variant="link-muted"+ size="icon-xs"+ className="shrink-0"+ aria-label={"More about " + item.label}+ />+ }+ >+ <Info />+ </TooltipTrigger>+ <TooltipContent>+ <div className="max-w-60">{item.hint}</div>+ </TooltipContent>+ </Tooltip>+ ) : null}+ </div>+ ))}+ </div>+ )}+ </div>+ );+}+"""+++def welcome_checklist_project() -> dict[str, Any]:+ """The checklist component's source project (kept publishable by a contract test)."""+ project = synthetic_source_project(_CHECKLIST_CODE)+ # The complete capability shape, not just the fields the checklist uses:+ # the builder freezes this verbatim into the artifact manifest, and older+ # clients parse the manifest with every field required.+ project["capabilities"] = {+ "posthog": {+ "insights": [],+ "inlineQueries": False,+ "captureEvents": [],+ "state": ["user"],+ "actions": [],+ },+ "network": {"origins": []},+ }+ project["component"] = {"size": {"defaultW": 2, "defaultH": 5, "minW": 2, "minH": 3}}+ return project+++def seed_home_canvas(canvas: Canvas, *, user: User, channel_id: UUID) -> None:+ """Publish the welcome checklist onto a freshly provisioned home canvas.++ Creates the checklist component in the user's personal channel, queues its+ build, pre-ticks what the account already answers, and publishes the home+ layout with the component placed 2x5 in the top-left corner. The placement+ goes live before the build finishes — the tile shows a spinner until the+ artifact lands, which beats opening onto an empty grid. Raises on failure;+ the caller treats seeding as best-effort.+ """+ component = Canvas.objects.create(+ team_id=canvas.team_id,+ channel_id=channel_id,+ name=WELCOME_COMPONENT_NAME,+ kind=Canvas.KIND_COMPONENT,+ description="Onboarding checklist walking a new user through their first steps in PostHog Desktop.",+ created_by=user,+ )+ build_service.publish_source_project(+ component,+ project=welcome_checklist_project(),+ prompt=WELCOME_COMPONENT_NAME,+ name=None,+ has_expected_version=False,+ expected_version_id=None,+ task_id=None,+ created_by=user,+ )+ CanvasState.objects.create(+ team_id=canvas.team_id,+ canvas=component,+ scope=CanvasState.SCOPE_USER,+ user=user,+ key=WELCOME_STATE_KEY,+ value={+ # They are reading the checklist inside the desktop app.+ "download-desktop": True,+ "connect-github": Integration.objects.filter(+ team_id=canvas.team_id, kind=Integration.IntegrationKind.GITHUB+ ).exists(),+ },+ )+ layout = default_layout()+ layout["placements"] = [+ {+ "id": "p-welcome",+ "status": "live",+ "x": 0,+ "y": 0,+ "w": 2,+ "h": 5,+ "component": str(component.id),+ "version": "latest",+ "prompt": WELCOME_COMPONENT_NAME,+ }+ ]+ build_service.publish_grid_layout(+ canvas,+ layout=layout,+ prompt=WELCOME_COMPONENT_NAME,+ has_expected_version=False,+ expected_version_id=None,+ task_id=None,+ created_by=user,+ )diff --git a/products/canvas/frontend/generated/api.schemas.ts b/products/canvas/frontend/generated/api.schemas.tsindex 4945ea76f320..62c92ce32233 100644--- a/products/canvas/frontend/generated/api.schemas.ts+++ b/products/canvas/frontend/generated/api.schemas.ts@@ -770,6 +770,321 @@ export interface CanvasPublishConflictApi {current_version_id: string | null}+/**+ * * `1` - 1+ */+export type CanvasLayoutSchemaVersionEnumApi =+ (typeof CanvasLayoutSchemaVersionEnumApi)[keyof typeof CanvasLayoutSchemaVersionEnumApi]++export const CanvasLayoutSchemaVersionEnumApi = {+ Number1: 1,+} as const++/**+ * * `4` - 4+ * * `6` - 6+ * * `8` - 8+ * * `10` - 10+ * * `12` - 12+ */+export type CanvasGridColumnsEnumApi = (typeof CanvasGridColumnsEnumApi)[keyof typeof CanvasGridColumnsEnumApi]++export const CanvasGridColumnsEnumApi = {+ Number4: 4,+ Number6: 6,+ Number8: 8,+ Number10: 10,+ Number12: 12,+} as const++/**+ * The grid a grid canvas lays its placements out on.+ */+export interface CanvasGridApi {+ /** Grid width in columns. One of 4, 6, 8, 10, or 12.+ *+ * * `4` - 4+ * * `6` - 6+ * * `8` - 8+ * * `10` - 10+ * * `12` - 12 */+ columns: CanvasGridColumnsEnumApi+ /**+ * Height of one grid row, in pixels.+ * @minimum 24+ * @maximum 400+ */+ rowHeight: number+ /**+ * Gap between placements, in pixels.+ * @minimum 0+ * @maximum 48+ */+ gap: number+}++/**+ * * `pending` - pending+ * * `generating` - generating+ * * `live` - live+ * * `failed` - failed+ */+export type CanvasPlacementStatusEnumApi =+ (typeof CanvasPlacementStatusEnumApi)[keyof typeof CanvasPlacementStatusEnumApi]++export const CanvasPlacementStatusEnumApi = {+ Pending: 'pending',+ Generating: 'generating',+ Live: 'live',+ Failed: 'failed',+} as const++/**+ * Per-placement settings, validated against the component's configSchema.+ * @nullable+ */+export type CanvasPlacementApiConfig = { [key: string]: unknown } | null++/**+ * One placed widget on a grid canvas.+ */+export interface CanvasPlacementApi {+ /**+ * Stable placement id, unique within the layout. 1-64 characters of letters, digits, '_', or '-'.+ * @maxLength 64+ * @pattern ^[A-Za-z0-9_-]{1,64}$+ */+ id: string+ /** Placement lifecycle: 'pending' (box drawn, no prompt yet), 'generating' (an agent task is filling it), 'live' (renders its component), 'failed' (generation failed; re-prompt or remove).+ *+ * * `pending` - pending+ * * `generating` - generating+ * * `live` - live+ * * `failed` - failed */+ status: CanvasPlacementStatusEnumApi+ /**+ * Id of the component canvas this placement renders. Required once the placement is live.+ * @nullable+ */+ component?: string | null+ /**+ * Component version to render: "latest" (the default — follows the component's published build) or a pinned source version id.+ * @nullable+ */+ version?: string | null+ /**+ * Left edge, in grid columns (0-based).+ * @minimum 0+ */+ x: number+ /**+ * Top edge, in grid rows (0-based).+ * @minimum 0+ */+ y: number+ /**+ * Width, in grid columns.+ * @minimum 1+ */+ w: number+ /**+ * Height, in grid rows.+ * @minimum 1+ */+ h: number+ /**+ * Per-placement settings, validated against the component's configSchema.+ * @nullable+ */+ config?: CanvasPlacementApiConfig+ /**+ * For pending/generating/failed placements: what the user asked this box to become.+ * @maxLength 10000+ * @nullable+ */+ prompt?: string | null+ /**+ * Id of the agent task currently filling this placement, when one is running.+ * @nullable+ */+ generationTaskId?: string | null+}++/**+ * A grid canvas's layout document — its entire 'source'.+ */+export interface CanvasLayoutApi {+ /** Layout schema version. Currently always 1.+ *+ * * `1` - 1 */+ schemaVersion: CanvasLayoutSchemaVersionEnumApi+ /** The grid placements are laid out on. */+ grid: CanvasGridApi+ /** The placed widgets, at most 24. Placements may not overlap or extend past the grid. */+ placements: CanvasPlacementApi[]+}++/**+ * A grid canvas's layout plus the version pointer edits must be based on.+ */+export interface CanvasLayoutResponseApi {+ /** Identity and version pointers for the canvas. */+ canvas: CanvasSummaryApi+ /** The layout document. A grid canvas with no versions yet returns the default empty layout. */+ layout: CanvasLayoutApi+ /**+ * The live layout version this document reflects — pass as expected_current_version_id when publishing or patching. Null before the first layout publish.+ * @nullable+ */+ current_version_id: string | null+}++/**+ * * `set_grid` - set_grid+ * * `add_placement` - add_placement+ * * `update_placement` - update_placement+ * * `remove_placement` - remove_placement+ */+export type CanvasLayoutOpEnumApi = (typeof CanvasLayoutOpEnumApi)[keyof typeof CanvasLayoutOpEnumApi]++export const CanvasLayoutOpEnumApi = {+ SetGrid: 'set_grid',+ AddPlacement: 'add_placement',+ UpdatePlacement: 'update_placement',+ RemovePlacement: 'remove_placement',+} as const++/**+ * Per-placement settings, validated against the component's configSchema.+ * @nullable+ */+export type CanvasPlacementChangesApiConfig = { [key: string]: unknown } | null++/**+ * Fields to merge into an existing placement (all optional; id cannot change).+ */+export interface CanvasPlacementChangesApi {+ /** Placement lifecycle: 'pending' (box drawn, no prompt yet), 'generating' (an agent task is filling it), 'live' (renders its component), 'failed' (generation failed; re-prompt or remove).+ *+ * * `pending` - pending+ * * `generating` - generating+ * * `live` - live+ * * `failed` - failed */+ status?: CanvasPlacementStatusEnumApi+ /**+ * Id of the component canvas this placement renders. Required once the placement is live.+ * @nullable+ */+ component?: string | null+ /**+ * Component version to render: "latest" (the default — follows the component's published build) or a pinned source version id.+ * @nullable+ */+ version?: string | null+ /**+ * Left edge, in grid columns (0-based).+ * @minimum 0+ */+ x?: number+ /**+ * Top edge, in grid rows (0-based).+ * @minimum 0+ */+ y?: number+ /**+ * Width, in grid columns.+ * @minimum 1+ */+ w?: number+ /**+ * Height, in grid rows.+ * @minimum 1+ */+ h?: number+ /**+ * Per-placement settings, validated against the component's configSchema.+ * @nullable+ */+ config?: CanvasPlacementChangesApiConfig+ /**+ * For pending/generating/failed placements: what the user asked this box to become.+ * @maxLength 10000+ * @nullable+ */+ prompt?: string | null+ /**+ * Id of the agent task currently filling this placement, when one is running.+ * @nullable+ */+ generationTaskId?: string | null+}++/**+ * One surgical layout operation.+ */+export interface CanvasLayoutPatchOperationApi {+ /** The operation to apply.+ *+ * * `set_grid` - set_grid+ * * `add_placement` - add_placement+ * * `update_placement` - update_placement+ * * `remove_placement` - remove_placement */+ op: CanvasLayoutOpEnumApi+ /** For set_grid: the new grid definition. */+ grid?: CanvasGridApi+ /** For add_placement: the placement to add. */+ placement?: CanvasPlacementApi+ /**+ * For update_placement/remove_placement: the target placement id.+ * @maxLength 64+ */+ id?: string+ /** For update_placement: the fields to merge into the placement. */+ changes?: CanvasPlacementChangesApi+}++/**+ * Payload for applying surgical operations to the canvas's current layout.+ */+export interface CanvasLayoutPatchApi {+ /** Operations applied in order to the canvas's current layout, at most 64. */+ operations: CanvasLayoutPatchOperationApi[]+ /** Short description of the change, stored on the appended version history entry. */+ prompt?: string+ /**+ * Required optimistic-concurrency guard: the current_version_id the operations are based on (null when the canvas has no layout versions yet). A moved head is rejected with 409 version_conflict — patches cannot apply unguarded.+ * @nullable+ */+ expected_current_version_id: string | null+}++/**+ * Result of a successful layout publish or patch. The new version is live immediately — no build runs.+ */+export interface CanvasLayoutPublishResponseApi {+ /** The canvas after the publish, including the new version pointer. */+ canvas: CanvasSummaryApi+ /** The layout document as published. */+ layout: CanvasLayoutApi+ /** Id of the layout version this publish created. */+ current_version_id: string+}++/**+ * Payload for publishing a complete layout document.+ */+export interface CanvasLayoutPublishApi {+ /** The complete layout document to publish. */+ layout: CanvasLayoutApi+ /** Short description of the change, stored on the appended version history entry. */+ prompt?: string+ /**+ * Optimistic-concurrency guard: the current_version_id the layout was based on (null when the canvas has no versions yet). A moved head is rejected with 409 version_conflict. Omit to publish unguarded.+ * @nullable+ */+ expected_current_version_id?: string | null+}+/*** Payload for promoting a draft version to the canvas's live head.*/@@ -1131,6 +1446,13 @@ export type CanvasesDraftsRetrieveParams = {offset?: number}+export type CanvasesLayoutRetrieveParams = {+ /**+ * Read this historical layout version instead of the head (for version browsing).+ */+ version_id?: string+}+export type CanvasesSourceRetrieveParams = {/*** Read this historical source version instead of the head (for version browsing).diff --git a/products/canvas/frontend/generated/api.ts b/products/canvas/frontend/generated/api.tsindex 181bb9027fda..2799529999b4 100644--- a/products/canvas/frontend/generated/api.ts+++ b/products/canvas/frontend/generated/api.ts@@ -21,6 +21,10 @@ import type {CanvasCreateApi,CanvasErrorReportResultApi,CanvasFixRequestResultApi,+ CanvasLayoutPatchApi,+ CanvasLayoutPublishApi,+ CanvasLayoutPublishResponseApi,+ CanvasLayoutResponseApi,CanvasPromoteApi,CanvasPublishCurrentVersionApi,CanvasReportErrorApi,@@ -39,6 +43,7 @@ import type {CanvasValidateResponseApi,CanvasesBuildsRetrieveParams,CanvasesDraftsRetrieveParams,+ CanvasesLayoutRetrieveParams,CanvasesListParams,CanvasesSourceRetrieveParams,CanvasesStateRetrieveParams,@@ -327,6 +332,93 @@ export const canvasesEditCreate = async (})}+export const getCanvasesLayoutRetrieveUrl = (projectId: string, id: string, params?: CanvasesLayoutRetrieveParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/canvases/${id}/layout/?${stringifiedParams}`+ : `/api/projects/${projectId}/canvases/${id}/layout/`+}++/**+ * Read a grid canvas's layout document and its `current_version_id`.+ *+ * Always call this before editing: pass the returned version id as+ * `expected_current_version_id` on publish/patch so concurrent edits are+ * not overwritten. A grid canvas with no versions yet returns the+ * default empty layout with a null version id.+ */+export const canvasesLayoutRetrieve = async (+ projectId: string,+ id: string,+ params?: CanvasesLayoutRetrieveParams,+ options?: RequestInit+): Promise<CanvasLayoutResponseApi> => {+ return apiMutator<CanvasLayoutResponseApi>(getCanvasesLayoutRetrieveUrl(projectId, id, params), {+ ...options,+ method: 'GET',+ })+}++export const getCanvasesLayoutPatchCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/canvases/${id}/layout/patch/`+}++/**+ * Apply surgical operations to the grid canvas's current layout.+ *+ * The default write path for both the editor and agents: add, move,+ * resize, fill, or remove one placement without resending the layout.+ * `expected_current_version_id` is mandatory so an agent filling a box+ * and a user rearranging widgets cannot overwrite each other.+ */+export const canvasesLayoutPatchCreate = async (+ projectId: string,+ id: string,+ canvasLayoutPatchApi: CanvasLayoutPatchApi,+ options?: RequestInit+): Promise<CanvasLayoutPublishResponseApi> => {+ return apiMutator<CanvasLayoutPublishResponseApi>(getCanvasesLayoutPatchCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(canvasLayoutPatchApi),+ })+}++export const getCanvasesLayoutPublishCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/canvases/${id}/layout/publish/`+}++/**+ * Publish a complete layout document as the grid canvas's new head version.+ *+ * Layout is data, not code: the new version is live immediately, with no+ * build. Validation errors reject the publish (400) and leave the canvas+ * untouched; a stale `expected_current_version_id` is rejected with 409.+ */+export const canvasesLayoutPublishCreate = async (+ projectId: string,+ id: string,+ canvasLayoutPublishApi: CanvasLayoutPublishApi,+ options?: RequestInit+): Promise<CanvasLayoutPublishResponseApi> => {+ return apiMutator<CanvasLayoutPublishResponseApi>(getCanvasesLayoutPublishCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(canvasLayoutPublishApi),+ })+}+export const getCanvasesPromoteCreateUrl = (projectId: string, id: string) => {return `/api/projects/${projectId}/canvases/${id}/promote/`}@@ -660,3 +752,21 @@ export const canvasesActionsRetrieve = async (method: 'GET',})}++export const getCanvasesHomeCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/canvases/home/`+}++/**+ * Get or provision the caller's home canvas.+ *+ * Idempotent: returns the user's existing home canvas, or creates a grid+ * canvas in their personal channel and points their home preference at+ * it. The home surface calls this on open.+ */+export const canvasesHomeCreate = async (projectId: string, options?: RequestInit): Promise<CanvasApi> => {+ return apiMutator<CanvasApi>(getCanvasesHomeCreateUrl(projectId), {+ ...options,+ method: 'POST',+ })+}diff --git a/products/canvas/frontend/generated/api.zod.ts b/products/canvas/frontend/generated/api.zod.tsindex 9f74eb6d6ea5..e6f6a4c71192 100644--- a/products/canvas/frontend/generated/api.zod.ts+++ b/products/canvas/frontend/generated/api.zod.ts@@ -353,6 +353,352 @@ export const CanvasesEditCreateBody = /* @__PURE__ */ zod}).describe("Payload for publishing per-file edits against the canvas's current source.")+/**+ * Apply surgical operations to the grid canvas's current layout.+ *+ * The default write path for both the editor and agents: add, move,+ * resize, fill, or remove one placement without resending the layout.+ * `expected_current_version_id` is mandatory so an agent filling a box+ * and a user rearranging widgets cannot overwrite each other.+ */+export const canvasesLayoutPatchCreateBodyOperationsItemGridOneRowHeightMin = 24+export const canvasesLayoutPatchCreateBodyOperationsItemGridOneRowHeightMax = 400++export const canvasesLayoutPatchCreateBodyOperationsItemGridOneGapMin = 0+export const canvasesLayoutPatchCreateBodyOperationsItemGridOneGapMax = 48++export const canvasesLayoutPatchCreateBodyOperationsItemPlacementOneIdMax = 64++export const canvasesLayoutPatchCreateBodyOperationsItemPlacementOneIdRegExp = new RegExp('^[A-Za-z0-9_-]{1,64}$')+export const canvasesLayoutPatchCreateBodyOperationsItemPlacementOneXMin = 0++export const canvasesLayoutPatchCreateBodyOperationsItemPlacementOneYMin = 0++export const canvasesLayoutPatchCreateBodyOperationsItemPlacementOnePromptMax = 10000++export const canvasesLayoutPatchCreateBodyOperationsItemIdMax = 64++export const canvasesLayoutPatchCreateBodyOperationsItemChangesOneXMin = 0++export const canvasesLayoutPatchCreateBodyOperationsItemChangesOneYMin = 0++export const canvasesLayoutPatchCreateBodyOperationsItemChangesOnePromptMax = 10000++export const CanvasesLayoutPatchCreateBody = /* @__PURE__ */ zod+ .object({+ operations: zod+ .array(+ zod+ .object({+ op: zod+ .enum(['set_grid', 'add_placement', 'update_placement', 'remove_placement'])+ .describe(+ '\* `set_grid` - set_grid\n\* `add_placement` - add_placement\n\* `update_placement` - update_placement\n\* `remove_placement` - remove_placement'+ )+ .describe(+ 'The operation to apply.\n\n\* `set_grid` - set_grid\n\* `add_placement` - add_placement\n\* `update_placement` - update_placement\n\* `remove_placement` - remove_placement'+ ),+ grid: zod+ .object({+ columns: zod+ .union([+ zod.literal(4),+ zod.literal(6),+ zod.literal(8),+ zod.literal(10),+ zod.literal(12),+ ])+ .describe('\* `4` - 4\n\* `6` - 6\n\* `8` - 8\n\* `10` - 10\n\* `12` - 12')+ .describe(+ 'Grid width in columns. One of 4, 6, 8, 10, or 12.\n\n\* `4` - 4\n\* `6` - 6\n\* `8` - 8\n\* `10` - 10\n\* `12` - 12'+ ),+ rowHeight: zod+ .number()+ .min(canvasesLayoutPatchCreateBodyOperationsItemGridOneRowHeightMin)+ .max(canvasesLayoutPatchCreateBodyOperationsItemGridOneRowHeightMax)+ .describe('Height of one grid row, in pixels.'),+ gap: zod+ .number()+ .min(canvasesLayoutPatchCreateBodyOperationsItemGridOneGapMin)+ .max(canvasesLayoutPatchCreateBodyOperationsItemGridOneGapMax)+ .describe('Gap between placements, in pixels.'),+ })+ .describe('The grid a grid canvas lays its placements out on.')+ .optional()+ .describe('For set_grid: the new grid definition.'),+ placement: zod+ .object({+ id: zod+ .string()+ .max(canvasesLayoutPatchCreateBodyOperationsItemPlacementOneIdMax)+ .regex(canvasesLayoutPatchCreateBodyOperationsItemPlacementOneIdRegExp)+ .describe(+ "Stable placement id, unique within the layout. 1-64 characters of letters, digits, '_', or '-'."+ ),+ status: zod+ .enum(['pending', 'generating', 'live', 'failed'])+ .describe(+ '\* `pending` - pending\n\* `generating` - generating\n\* `live` - live\n\* `failed` - failed'+ )+ .describe(+ "Placement lifecycle: 'pending' (box drawn, no prompt yet), 'generating' (an agent task is filling it), 'live' (renders its component), 'failed' (generation failed; re-prompt or remove).\n\n\* `pending` - pending\n\* `generating` - generating\n\* `live` - live\n\* `failed` - failed"+ ),+ component: zod+ .string()+ .nullish()+ .describe(+ 'Id of the component canvas this placement renders. Required once the placement is live.'+ ),+ version: zod+ .string()+ .nullish()+ .describe(+ 'Component version to render: \"latest\" (the default — follows the component\'s published build) or a pinned source version id.'+ ),+ x: zod+ .number()+ .min(canvasesLayoutPatchCreateBodyOperationsItemPlacementOneXMin)+ .describe('Left edge, in grid columns (0-based).'),+ y: zod+ .number()+ .min(canvasesLayoutPatchCreateBodyOperationsItemPlacementOneYMin)+ .describe('Top edge, in grid rows (0-based).'),+ w: zod.number().min(1).describe('Width, in grid columns.'),+ h: zod.number().min(1).describe('Height, in grid rows.'),+ config: zod+ .record(zod.string(), zod.unknown())+ .nullish()+ .describe(+ "Per-placement settings, validated against the component's configSchema."+ ),+ prompt: zod+ .string()+ .max(canvasesLayoutPatchCreateBodyOperationsItemPlacementOnePromptMax)+ .nullish()+ .describe(+ 'For pending\/generating\/failed placements: what the user asked this box to become.'+ ),+ generationTaskId: zod+ .string()+ .nullish()+ .describe(+ 'Id of the agent task currently filling this placement, when one is running.'+ ),+ })+ .describe('One placed widget on a grid canvas.')+ .optional()+ .describe('For add_placement: the placement to add.'),+ id: zod+ .string()+ .max(canvasesLayoutPatchCreateBodyOperationsItemIdMax)+ .optional()+ .describe('For update_placement\/remove_placement: the target placement id.'),+ changes: zod+ .object({+ status: zod+ .enum(['pending', 'generating', 'live', 'failed'])+ .describe(+ '\* `pending` - pending\n\* `generating` - generating\n\* `live` - live\n\* `failed` - failed'+ )+ .optional()+ .describe(+ "Placement lifecycle: 'pending' (box drawn, no prompt yet), 'generating' (an agent task is filling it), 'live' (renders its component), 'failed' (generation failed; re-prompt or remove).\n\n\* `pending` - pending\n\* `generating` - generating\n\* `live` - live\n\* `failed` - failed"+ ),+ component: zod+ .string()+ .nullish()+ .describe(+ 'Id of the component canvas this placement renders. Required once the placement is live.'+ ),+ version: zod+ .string()+ .nullish()+ .describe(+ 'Component version to render: \"latest\" (the default — follows the component\'s published build) or a pinned source version id.'+ ),+ x: zod+ .number()+ .min(canvasesLayoutPatchCreateBodyOperationsItemChangesOneXMin)+ .optional()+ .describe('Left edge, in grid columns (0-based).'),+ y: zod+ .number()+ .min(canvasesLayoutPatchCreateBodyOperationsItemChangesOneYMin)+ .optional()+ .describe('Top edge, in grid rows (0-based).'),+ w: zod.number().min(1).optional().describe('Width, in grid columns.'),+ h: zod.number().min(1).optional().describe('Height, in grid rows.'),+ config: zod+ .record(zod.string(), zod.unknown())+ .nullish()+ .describe(+ "Per-placement settings, validated against the component's configSchema."+ ),+ prompt: zod+ .string()+ .max(canvasesLayoutPatchCreateBodyOperationsItemChangesOnePromptMax)+ .nullish()+ .describe(+ 'For pending\/generating\/failed placements: what the user asked this box to become.'+ ),+ generationTaskId: zod+ .string()+ .nullish()+ .describe(+ 'Id of the agent task currently filling this placement, when one is running.'+ ),+ })+ .describe('Fields to merge into an existing placement (all optional; id cannot change).')+ .optional()+ .describe('For update_placement: the fields to merge into the placement.'),+ })+ .describe('One surgical layout operation.')+ )+ .describe("Operations applied in order to the canvas's current layout, at most 64."),+ prompt: zod+ .string()+ .optional()+ .describe('Short description of the change, stored on the appended version history entry.'),+ expected_current_version_id: zod+ .string()+ .nullable()+ .describe(+ 'Required optimistic-concurrency guard: the current_version_id the operations are based on (null when the canvas has no layout versions yet). A moved head is rejected with 409 version_conflict — patches cannot apply unguarded.'+ ),+ })+ .describe("Payload for applying surgical operations to the canvas's current layout.")++/**+ * Publish a complete layout document as the grid canvas's new head version.+ *+ * Layout is data, not code: the new version is live immediately, with no+ * build. Validation errors reject the publish (400) and leave the canvas+ * untouched; a stale `expected_current_version_id` is rejected with 409.+ */+export const canvasesLayoutPublishCreateBodyLayoutOneGridOneRowHeightMin = 24+export const canvasesLayoutPublishCreateBodyLayoutOneGridOneRowHeightMax = 400++export const canvasesLayoutPublishCreateBodyLayoutOneGridOneGapMin = 0+export const canvasesLayoutPublishCreateBodyLayoutOneGridOneGapMax = 48++export const canvasesLayoutPublishCreateBodyLayoutOnePlacementsItemIdMax = 64++export const canvasesLayoutPublishCreateBodyLayoutOnePlacementsItemIdRegExp = new RegExp('^[A-Za-z0-9_-]{1,64}$')+export const canvasesLayoutPublishCreateBodyLayoutOnePlacementsItemXMin = 0++export const canvasesLayoutPublishCreateBodyLayoutOnePlacementsItemYMin = 0++export const canvasesLayoutPublishCreateBodyLayoutOnePlacementsItemPromptMax = 10000++export const CanvasesLayoutPublishCreateBody = /* @__PURE__ */ zod+ .object({+ layout: zod+ .object({+ schemaVersion: zod+ .literal(1)+ .describe('\* `1` - 1')+ .describe('Layout schema version. Currently always 1.\n\n\* `1` - 1'),+ grid: zod+ .object({+ columns: zod+ .union([zod.literal(4), zod.literal(6), zod.literal(8), zod.literal(10), zod.literal(12)])+ .describe('\* `4` - 4\n\* `6` - 6\n\* `8` - 8\n\* `10` - 10\n\* `12` - 12')+ .describe(+ 'Grid width in columns. One of 4, 6, 8, 10, or 12.\n\n\* `4` - 4\n\* `6` - 6\n\* `8` - 8\n\* `10` - 10\n\* `12` - 12'+ ),+ rowHeight: zod+ .number()+ .min(canvasesLayoutPublishCreateBodyLayoutOneGridOneRowHeightMin)+ .max(canvasesLayoutPublishCreateBodyLayoutOneGridOneRowHeightMax)+ .describe('Height of one grid row, in pixels.'),+ gap: zod+ .number()+ .min(canvasesLayoutPublishCreateBodyLayoutOneGridOneGapMin)+ .max(canvasesLayoutPublishCreateBodyLayoutOneGridOneGapMax)+ .describe('Gap between placements, in pixels.'),+ })+ .describe('The grid a grid canvas lays its placements out on.')+ .describe('The grid placements are laid out on.'),+ placements: zod+ .array(+ zod+ .object({+ id: zod+ .string()+ .max(canvasesLayoutPublishCreateBodyLayoutOnePlacementsItemIdMax)+ .regex(canvasesLayoutPublishCreateBodyLayoutOnePlacementsItemIdRegExp)+ .describe(+ "Stable placement id, unique within the layout. 1-64 characters of letters, digits, '_', or '-'."+ ),+ status: zod+ .enum(['pending', 'generating', 'live', 'failed'])+ .describe(+ '\* `pending` - pending\n\* `generating` - generating\n\* `live` - live\n\* `failed` - failed'+ )+ .describe(+ "Placement lifecycle: 'pending' (box drawn, no prompt yet), 'generating' (an agent task is filling it), 'live' (renders its component), 'failed' (generation failed; re-prompt or remove).\n\n\* `pending` - pending\n\* `generating` - generating\n\* `live` - live\n\* `failed` - failed"+ ),+ component: zod+ .string()+ .nullish()+ .describe(+ 'Id of the component canvas this placement renders. Required once the placement is live.'+ ),+ version: zod+ .string()+ .nullish()+ .describe(+ 'Component version to render: \"latest\" (the default — follows the component\'s published build) or a pinned source version id.'+ ),+ x: zod+ .number()+ .min(canvasesLayoutPublishCreateBodyLayoutOnePlacementsItemXMin)+ .describe('Left edge, in grid columns (0-based).'),+ y: zod+ .number()+ .min(canvasesLayoutPublishCreateBodyLayoutOnePlacementsItemYMin)+ .describe('Top edge, in grid rows (0-based).'),+ w: zod.number().min(1).describe('Width, in grid columns.'),+ h: zod.number().min(1).describe('Height, in grid rows.'),+ config: zod+ .record(zod.string(), zod.unknown())+ .nullish()+ .describe(+ "Per-placement settings, validated against the component's configSchema."+ ),+ prompt: zod+ .string()+ .max(canvasesLayoutPublishCreateBodyLayoutOnePlacementsItemPromptMax)+ .nullish()+ .describe(+ 'For pending\/generating\/failed placements: what the user asked this box to become.'+ ),+ generationTaskId: zod+ .string()+ .nullish()+ .describe(+ 'Id of the agent task currently filling this placement, when one is running.'+ ),+ })+ .describe('One placed widget on a grid canvas.')+ )+ .describe('The placed widgets, at most 24. Placements may not overlap or extend past the grid.'),+ })+ .describe("A grid canvas's layout document — its entire 'source'.")+ .describe('The complete layout document to publish.'),+ prompt: zod+ .string()+ .optional()+ .describe('Short description of the change, stored on the appended version history entry.'),+ expected_current_version_id: zod+ .string()+ .nullish()+ .describe(+ 'Optimistic-concurrency guard: the current_version_id the layout was based on (null when the canvas has no versions yet). A moved head is rejected with 409 version_conflict. Omit to publish unguarded.'+ ),+ })+ .describe('Payload for publishing a complete layout document.')+/*** Make a draft version the canvas's live head.*diff --git a/products/canvas/mcp/tools.yaml b/products/canvas/mcp/tools.yamlindex 27abf315f1be..a6dfeef2c7c8 100644--- a/products/canvas/mcp/tools.yaml+++ b/products/canvas/mcp/tools.yaml@@ -244,6 +244,18 @@ tools:canvases-destroy:operation: canvases_destroyenabled: false+ canvases-home-create:+ operation: canvases_home_create+ enabled: false+ canvases-layout-patch-create:+ operation: canvases_layout_patch_create+ enabled: false+ canvases-layout-publish-create:+ operation: canvases_layout_publish_create+ enabled: false+ canvases-layout-retrieve:+ operation: canvases_layout_retrieve+ enabled: falsecanvases-partial-update:operation: canvases_partial_updateenabled: falsediff --git a/products/canvas/packages/canvas_builder/manifest.json b/products/canvas/packages/canvas_builder/manifest.jsonindex dacd2a0220d0..73f6a2eed87f 100644--- a/products/canvas/packages/canvas_builder/manifest.json+++ b/products/canvas/packages/canvas_builder/manifest.json@@ -63,6 +63,7 @@"maxArtifactFileBytes": 4194304,"maxArtifactTotalBytes": 12582912,"maxStateValueBytes": 65536,- "maxStateKeysPerScope": 256+ "maxStateKeysPerScope": 256,+ "maxGridPlacements": 24}}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 68bbc4f328c1..deec3dad3961 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -15341,6 +15341,355 @@ export namespace Schemas {task_id: string;}+ /**+ * * `4` - 4+ * * `6` - 6+ * * `8` - 8+ * * `10` - 10+ * * `12` - 12+ */+ export type CanvasGridColumnsEnum = typeof CanvasGridColumnsEnum[keyof typeof CanvasGridColumnsEnum];+++ export const CanvasGridColumnsEnum = {+ Number4: 4,+ Number6: 6,+ Number8: 8,+ Number10: 10,+ Number12: 12,+ } as const;++ /**+ * The grid a grid canvas lays its placements out on.+ */+ export interface CanvasGrid {+ /** Grid width in columns. One of 4, 6, 8, 10, or 12.+ *+ * * `4` - 4+ * * `6` - 6+ * * `8` - 8+ * * `10` - 10+ * * `12` - 12 */+ columns: CanvasGridColumnsEnum;+ /**+ * Height of one grid row, in pixels.+ * @minimum 24+ * @maximum 400+ */+ rowHeight: number;+ /**+ * Gap between placements, in pixels.+ * @minimum 0+ * @maximum 48+ */+ gap: number;+ }++ /**+ * * `1` - 1+ */+ export type CanvasLayoutSchemaVersionEnum = typeof CanvasLayoutSchemaVersionEnum[keyof typeof CanvasLayoutSchemaVersionEnum];+++ export const CanvasLayoutSchemaVersionEnum = {+ Number1: 1,+ } as const;++ /**+ * * `pending` - pending+ * * `generating` - generating+ * * `live` - live+ * * `failed` - failed+ */+ export type CanvasPlacementStatusEnum = typeof CanvasPlacementStatusEnum[keyof typeof CanvasPlacementStatusEnum];+++ export const CanvasPlacementStatusEnum = {+ Pending: 'pending',+ Generating: 'generating',+ Live: 'live',+ Failed: 'failed',+ } as const;++ /**+ * Per-placement settings, validated against the component's configSchema.+ * @nullable+ */+ export type CanvasPlacementConfig = { [key: string]: unknown } | null;++ /**+ * One placed widget on a grid canvas.+ */+ export interface CanvasPlacement {+ /**+ * Stable placement id, unique within the layout. 1-64 characters of letters, digits, '_', or '-'.+ * @maxLength 64+ * @pattern ^[A-Za-z0-9_-]{1,64}$+ */+ id: string;+ /** Placement lifecycle: 'pending' (box drawn, no prompt yet), 'generating' (an agent task is filling it), 'live' (renders its component), 'failed' (generation failed; re-prompt or remove).+ *+ * * `pending` - pending+ * * `generating` - generating+ * * `live` - live+ * * `failed` - failed */+ status: CanvasPlacementStatusEnum;+ /**+ * Id of the component canvas this placement renders. Required once the placement is live.+ * @nullable+ */+ component?: string | null;+ /**+ * Component version to render: "latest" (the default — follows the component's published build) or a pinned source version id.+ * @nullable+ */+ version?: string | null;+ /**+ * Left edge, in grid columns (0-based).+ * @minimum 0+ */+ x: number;+ /**+ * Top edge, in grid rows (0-based).+ * @minimum 0+ */+ y: number;+ /**+ * Width, in grid columns.+ * @minimum 1+ */+ w: number;+ /**+ * Height, in grid rows.+ * @minimum 1+ */+ h: number;+ /**+ * Per-placement settings, validated against the component's configSchema.+ * @nullable+ */+ config?: CanvasPlacementConfig;+ /**+ * For pending/generating/failed placements: what the user asked this box to become.+ * @maxLength 10000+ * @nullable+ */+ prompt?: string | null;+ /**+ * Id of the agent task currently filling this placement, when one is running.+ * @nullable+ */+ generationTaskId?: string | null;+ }++ /**+ * A grid canvas's layout document — its entire 'source'.+ */+ export interface CanvasLayout {+ /** Layout schema version. Currently always 1.+ *+ * * `1` - 1 */+ schemaVersion: CanvasLayoutSchemaVersionEnum;+ /** The grid placements are laid out on. */+ grid: CanvasGrid;+ /** The placed widgets, at most 24. Placements may not overlap or extend past the grid. */+ placements: CanvasPlacement[];+ }++ /**+ * * `set_grid` - set_grid+ * * `add_placement` - add_placement+ * * `update_placement` - update_placement+ * * `remove_placement` - remove_placement+ */+ export type CanvasLayoutOpEnum = typeof CanvasLayoutOpEnum[keyof typeof CanvasLayoutOpEnum];+++ export const CanvasLayoutOpEnum = {+ SetGrid: 'set_grid',+ AddPlacement: 'add_placement',+ UpdatePlacement: 'update_placement',+ RemovePlacement: 'remove_placement',+ } as const;++ /**+ * Per-placement settings, validated against the component's configSchema.+ * @nullable+ */+ export type CanvasPlacementChangesConfig = { [key: string]: unknown } | null;++ /**+ * Fields to merge into an existing placement (all optional; id cannot change).+ */+ export interface CanvasPlacementChanges {+ /** Placement lifecycle: 'pending' (box drawn, no prompt yet), 'generating' (an agent task is filling it), 'live' (renders its component), 'failed' (generation failed; re-prompt or remove).+ *+ * * `pending` - pending+ * * `generating` - generating+ * * `live` - live+ * * `failed` - failed */+ status?: CanvasPlacementStatusEnum;+ /**+ * Id of the component canvas this placement renders. Required once the placement is live.+ * @nullable+ */+ component?: string | null;+ /**+ * Component version to render: "latest" (the default — follows the component's published build) or a pinned source version id.+ * @nullable+ */+ version?: string | null;+ /**+ * Left edge, in grid columns (0-based).+ * @minimum 0+ */+ x?: number;+ /**+ * Top edge, in grid rows (0-based).+ * @minimum 0+ */+ y?: number;+ /**+ * Width, in grid columns.+ * @minimum 1+ */+ w?: number;+ /**+ * Height, in grid rows.+ * @minimum 1+ */+ h?: number;+ /**+ * Per-placement settings, validated against the component's configSchema.+ * @nullable+ */+ config?: CanvasPlacementChangesConfig;+ /**+ * For pending/generating/failed placements: what the user asked this box to become.+ * @maxLength 10000+ * @nullable+ */+ prompt?: string | null;+ /**+ * Id of the agent task currently filling this placement, when one is running.+ * @nullable+ */+ generationTaskId?: string | null;+ }++ /**+ * One surgical layout operation.+ */+ export interface CanvasLayoutPatchOperation {+ /** The operation to apply.+ *+ * * `set_grid` - set_grid+ * * `add_placement` - add_placement+ * * `update_placement` - update_placement+ * * `remove_placement` - remove_placement */+ op: CanvasLayoutOpEnum;+ /** For set_grid: the new grid definition. */+ grid?: CanvasGrid;+ /** For add_placement: the placement to add. */+ placement?: CanvasPlacement;+ /**+ * For update_placement/remove_placement: the target placement id.+ * @maxLength 64+ */+ id?: string;+ /** For update_placement: the fields to merge into the placement. */+ changes?: CanvasPlacementChanges;+ }++ /**+ * Payload for applying surgical operations to the canvas's current layout.+ */+ export interface CanvasLayoutPatch {+ /** Operations applied in order to the canvas's current layout, at most 64. */+ operations: CanvasLayoutPatchOperation[];+ /** Short description of the change, stored on the appended version history entry. */+ prompt?: string;+ /**+ * Required optimistic-concurrency guard: the current_version_id the operations are based on (null when the canvas has no layout versions yet). A moved head is rejected with 409 version_conflict — patches cannot apply unguarded.+ * @nullable+ */+ expected_current_version_id: string | null;+ }++ /**+ * Payload for publishing a complete layout document.+ */+ export interface CanvasLayoutPublish {+ /** The complete layout document to publish. */+ layout: CanvasLayout;+ /** Short description of the change, stored on the appended version history entry. */+ prompt?: string;+ /**+ * Optimistic-concurrency guard: the current_version_id the layout was based on (null when the canvas has no versions yet). A moved head is rejected with 409 version_conflict. Omit to publish unguarded.+ * @nullable+ */+ expected_current_version_id?: string | null;+ }++ /**+ * Identity and version pointers for one canvas.+ */+ export interface CanvasSummary {+ /** The canvas's id. */+ id: string;+ /** Display name of the canvas. */+ name: string;+ /** The canvas's kind (freeform, component, or grid).+ *+ * * `freeform` - freeform+ * * `grid` - grid+ * * `component` - component */+ kind: CanvasKindEnum;+ /** Id of the channel the canvas belongs to. */+ channel_id: string;+ /**+ * Id of the live source version — pass as expected_current_version_id on publish. Null before the first publish.+ * @nullable+ */+ current_version_id: string | null;+ /**+ * Id of the canvas's live (last successful, still-eligible) build. Null until a build completes.+ * @nullable+ */+ published_build_id: string | null;+ /** When the canvas was created. */+ created_at: string;+ /** Canonical link to the canvas in the PostHog app. The only valid way to link to a canvas — share this when pointing a user at it; never construct a canvas URL. */+ readonly url: string;+ }++ /**+ * Result of a successful layout publish or patch. The new version is live immediately — no build runs.+ */+ export interface CanvasLayoutPublishResponse {+ /** The canvas after the publish, including the new version pointer. */+ canvas: CanvasSummary;+ /** The layout document as published. */+ layout: CanvasLayout;+ /** Id of the layout version this publish created. */+ current_version_id: string;+ }++ /**+ * A grid canvas's layout plus the version pointer edits must be based on.+ */+ export interface CanvasLayoutResponse {+ /** Identity and version pointers for the canvas. */+ canvas: CanvasSummary;+ /** The layout document. A grid canvas with no versions yet returns the default empty layout. */+ layout: CanvasLayout;+ /**+ * The live layout version this document reflects — pass as expected_current_version_id when publishing or patching. Null before the first layout publish.+ * @nullable+ */+ current_version_id: string | null;+ }+/*** Payload for promoting a draft version to the canvas's live head.*/@@ -15585,38 +15934,6 @@ export namespace Schemas {expected_current_version_id?: string | null;}- /**- * Identity and version pointers for one canvas.- */- export interface CanvasSummary {- /** The canvas's id. */- id: string;- /** Display name of the canvas. */- name: string;- /** The canvas's kind (freeform, component, or grid).- *- * * `freeform` - freeform- * * `grid` - grid- * * `component` - component */- kind: CanvasKindEnum;- /** Id of the channel the canvas belongs to. */- channel_id: string;- /**- * Id of the live source version — pass as expected_current_version_id on publish. Null before the first publish.- * @nullable- */- current_version_id: string | null;- /**- * Id of the canvas's live (last successful, still-eligible) build. Null until a build completes.- * @nullable- */- published_build_id: string | null;- /** When the canvas was created. */- created_at: string;- /** Canonical link to the canvas in the PostHog app. The only valid way to link to a canvas — share this when pointing a user at it; never construct a canvas URL. */- readonly url: string;- }-/*** Result of a successful source-project publish.*/@@ -84693,6 +85010,13 @@ export namespace Schemas {offset?: number;};+ export type CanvasesLayoutRetrieveParams = {+ /**+ * Read this historical layout version instead of the head (for version browsing).+ */+ version_id?: string;+ };+export type CanvasesSourceRetrieveParams = {/*** Read this historical source version instead of the head (for version browsing).