: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): component store backend (#83543)
Peter Kirkham00fd96cf9a57
diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex bc3d69285fd4..98516564c85b 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -687,6 +687,8 @@ SPECTACULAR_SETTINGS = {"PropertyGroupOperator": ["AND", "OR"],# `scope`/`state` are generic field names; one shared name for the canvas state scope set."CanvasStateScopeEnum": ["user", "shared"],+ # `kind` is a generic field name; one shared name for the canvas kind set.+ "CanvasKindEnum": ["freeform", "grid", "component"],# `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 a11066bda3b1..48d7aa643d26 100644--- a/products/canvas/backend/build_service.py+++ b/products/canvas/backend/build_service.py@@ -480,6 +480,7 @@ def publish_source_project(prompt=prompt or None,created_by=created_by,capabilities=project.get("capabilities") or {},+ component_meta=project.get("component"),)build = _queue_build(version)@@ -626,6 +627,7 @@ def create_draft_version(prompt=prompt or None,created_by=created_by,capabilities=project.get("capabilities") or {},+ component_meta=project.get("component"),)build = _queue_build(version)@@ -795,7 +797,7 @@ def run_canvas_build(team_id: int, build_id: str) -> None:CanvasBuild.objects.for_team(team_id).select_for_update().filter(id=build_id)- .select_related("source_version")+ .select_related("source_version", "canvas").first())if build is None:@@ -822,7 +824,7 @@ def run_canvas_build(team_id: int, build_id: str) -> None:)return- diagnostics = validate_source_project(project)+ diagnostics = validate_source_project(project, kind=build.canvas.kind)if has_errors(diagnostics):_finish_failed(build, diagnostics)returndiff --git a/products/canvas/backend/contract.py b/products/canvas/backend/contract.pyindex d4e9187ec2b1..6b187fe6ebec 100644--- a/products/canvas/backend/contract.py+++ b/products/canvas/backend/contract.py@@ -19,6 +19,10 @@ from django.conf import settingsCANVAS_BUILDER_DIR = Path(settings.CANVAS_BUILDER_DIR)+GRID_COLUMN_CHOICES = (4, 6, 8, 10, 12)+MAX_COMPONENT_WIDTH = max(GRID_COLUMN_CHOICES)+MAX_COMPONENT_HEIGHT = 40+# A public DNS name is one or more dot-separated labels of ASCII letters, digits,# and hyphens (IDNA names stay in this set), with an optional trailing dot. Any# other character is rejected because urlsplit keeps CSP delimiters such as ";"diff --git a/products/canvas/backend/presentation/serializers.py b/products/canvas/backend/presentation/serializers.pyindex 016701c016f9..a8db7b437a6f 100644--- a/products/canvas/backend/presentation/serializers.py+++ b/products/canvas/backend/presentation/serializers.py@@ -2,11 +2,17 @@ from typing import Anyfrom django.conf import settings+from drf_spectacular.utils import extend_schema_fieldfrom rest_framework import serializersfrom posthog.api.shared import UserBasicSerializer-from products.canvas.backend.contract import canvas_sdk_version, contract_limits+from products.canvas.backend.contract import (+ MAX_COMPONENT_HEIGHT,+ MAX_COMPONENT_WIDTH,+ canvas_sdk_version,+ contract_limits,+)from products.canvas.backend.models import Canvas, CanvasState# Base64 expands 3 source bytes into 4 characters (padded); size the asset field@@ -25,10 +31,70 @@ def canvas_url(canvas: Canvas) -> str:return f"{settings.SITE_URL}/code/canvas/{canvas.channel_id}/{canvas.id}"+class CanvasComponentSizeSerializer(serializers.Serializer):+ """A component's grid-size contract, in grid units."""++ defaultW = serializers.IntegerField(+ min_value=1, max_value=MAX_COMPONENT_WIDTH, help_text="Width a new placement starts at, in grid columns."+ )+ defaultH = serializers.IntegerField(+ min_value=1, max_value=MAX_COMPONENT_HEIGHT, help_text="Height a new placement starts at, in grid rows."+ )+ minW = serializers.IntegerField(+ min_value=1, max_value=MAX_COMPONENT_WIDTH, help_text="Narrowest width the component renders usefully at."+ )+ minH = serializers.IntegerField(+ min_value=1, max_value=MAX_COMPONENT_HEIGHT, help_text="Shortest height the component renders usefully at."+ )+ maxW = serializers.IntegerField(+ required=False,+ min_value=1,+ max_value=MAX_COMPONENT_WIDTH,+ help_text="Widest allowed width; omit for no cap below the grid's width.",+ )+ maxH = serializers.IntegerField(+ required=False,+ min_value=1,+ max_value=MAX_COMPONENT_HEIGHT,+ help_text="Tallest allowed height; omit for no cap.",+ )+++class CanvasComponentMetaSerializer(serializers.Serializer):+ """A component's placement contract: how grid canvases may place and configure it."""++ size = CanvasComponentSizeSerializer(help_text="Grid-size contract for placements of this component.")+ configSchema = serializers.DictField(+ required=False,+ help_text=(+ 'JSON Schema ("type": "object") for a placement\'s config. The host validates each '+ "placement's config against it and passes the validated object to the widget at mount."+ ),+ )++class CanvasSerializer(serializers.ModelSerializer):"""A canvas document. Version/build content hangs off the source and build endpoints."""channel = serializers.UUIDField(source="channel_id", read_only=True)+ kind = serializers.ChoiceField(+ choices=Canvas.KINDS,+ read_only=True,+ help_text=(+ "What the canvas is: 'freeform' (a standalone app), 'component' (a reusable widget grids place), "+ "or 'grid' (a composition of components)."+ ),+ )+ description = serializers.CharField(+ read_only=True,+ help_text="Short prose describing the canvas. For components, the store-search text.",+ )+ component_meta = serializers.SerializerMethodField(+ help_text=(+ "For component-kind canvases: the head version's placement contract "+ "(size, optional configSchema). Null for other kinds and unpublished components."+ ),+ )current_version_id = serializers.UUIDField(source="current_source_version_id",read_only=True,@@ -49,6 +115,8 @@ class CanvasSerializer(serializers.ModelSerializer):fields = ["id","name",+ "kind",+ "description","channel","template_id","context",@@ -57,6 +125,7 @@ class CanvasSerializer(serializers.ModelSerializer):"pinned_at","current_version_id","published_build_id",+ "component_meta","created_by","created_at","updated_at",@@ -70,6 +139,12 @@ class CanvasSerializer(serializers.ModelSerializer):def get_url(self, canvas: Canvas) -> str:return canvas_url(canvas)+ @extend_schema_field(CanvasComponentMetaSerializer(allow_null=True))+ def get_component_meta(self, canvas: Canvas) -> dict | None:+ if canvas.kind != Canvas.KIND_COMPONENT or canvas.current_source_version is None:+ return None+ return canvas.current_source_version.component_meta+class CanvasCreateSerializer(serializers.Serializer):"""Payload for creating a new, empty canvas in a channel."""@@ -81,6 +156,26 @@ class CanvasCreateSerializer(serializers.Serializer):help_text="Display name for the canvas.",)channel_id = serializers.UUIDField(help_text="Id of the channel the canvas belongs to.")+ kind = serializers.ChoiceField(+ choices=Canvas.KINDS,+ required=False,+ default=Canvas.KIND_FREEFORM,+ help_text=(+ "What to create: 'freeform' (a standalone app), 'component' (a reusable widget for grids — "+ "its published project must declare a `component` placement contract), or 'grid' "+ "(a composition of components, edited through the layout endpoints)."+ ),+ )+ description = serializers.CharField(+ required=False,+ allow_blank=True,+ default="",+ trim_whitespace=True,+ help_text=(+ "Short prose describing the canvas. For components this is the store-search text agents "+ "match against — say what the widget shows and what its config controls."+ ),+ )template_id = serializers.CharField(required=False, default="freeform", max_length=64, help_text="Canvas template identifier.")@@ -101,6 +196,12 @@ class CanvasUpdateSerializer(serializers.Serializer):context = serializers.CharField( # type: ignore[assignment]required=False, allow_blank=True, trim_whitespace=False, help_text="Updated author context markdown.")+ description = serializers.CharField(+ required=False,+ allow_blank=True,+ trim_whitespace=True,+ help_text="Updated canvas description (for components, the store-search text).",+ )pinned = serializers.BooleanField(required=False, help_text="Whether the canvas is pinned in its channel.")generation_task_id = serializers.UUIDField(required=False, allow_null=True, help_text="Task currently generating this canvas, or null to clear it."@@ -196,6 +297,13 @@ class CanvasSourceProjectSerializer(serializers.Serializer):default=canvas_sdk_version,help_text="Version of the host-injected `ph` canvas SDK the project targets.",)+ component = CanvasComponentMetaSerializer(+ required=False,+ help_text=(+ "Placement contract, required for (and only allowed on) component-kind canvases: "+ "the grid size the component takes and the JSON Schema of its per-placement config."+ ),+ )capabilities = CanvasCapabilitiesSerializer(required=False,default=lambda: {@@ -244,6 +352,7 @@ class CanvasSummarySerializer(serializers.Serializer):id = serializers.UUIDField(help_text="The canvas's id.")name = serializers.CharField(help_text="Display name of the canvas.")+ kind = serializers.ChoiceField(choices=Canvas.KINDS, help_text="The canvas's kind (freeform, component, or grid).")channel_id = serializers.UUIDField(help_text="Id of the channel the canvas belongs to.")current_version_id = serializers.CharField(allow_null=True,@@ -471,6 +580,11 @@ class CanvasArtifactManifestSerializer(serializers.Serializer):capabilities = serializers.DictField(help_text="Declared PostHog/network capabilities the artifact is held to at runtime.",)+ component = serializers.DictField(+ required=False,+ allow_null=True,+ help_text="For component artifacts: the placement contract (size, configSchema) frozen into the build.",+ )class CanvasBuildSerializer(serializers.Serializer):diff --git a/products/canvas/backend/presentation/views.py b/products/canvas/backend/presentation/views.pyindex 784db3ab0f40..f492b45aa291 100644--- a/products/canvas/backend/presentation/views.py+++ b/products/canvas/backend/presentation/views.py@@ -120,6 +120,20 @@ 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."""+ 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,+ )++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@@ -150,7 +164,8 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):scope_object = "canvas"# unscoped() because a class attribute is built before any team context# exists; safely_get_queryset applies the team filter explicitly.- queryset = Canvas.objects.unscoped().select_related("created_by")+ # current_source_version feeds the component_meta field on every row.+ 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"]@@ -209,6 +224,19 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):OpenApiParameter("channel", OpenApiTypes.UUID, required=False, description="Only return canvases in this channel."),+ OpenApiParameter(+ "kind",+ OpenApiTypes.STR,+ required=False,+ enum=Canvas.KINDS,+ description="Only return canvases of this kind. kind=component lists the component store.",+ ),+ OpenApiParameter(+ "search",+ OpenApiTypes.STR,+ required=False,+ description="Only return canvases whose name or description contains this text (case-insensitive).",+ ),])def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:@@ -253,6 +281,14 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):except ValueError:return queryset.none()queryset = queryset.filter(channel_id=channel_id)+ kind = self.request.query_params.get("kind")+ if kind:+ if kind not in Canvas.KINDS:+ return queryset.none()+ queryset = queryset.filter(kind=kind)+ search = self.request.query_params.get("search")+ if search:+ queryset = queryset.filter(Q(name__icontains=search) | Q(description__icontains=search))return queryset.order_by("-created_at")@extend_schema(@@ -288,6 +324,8 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):team_id=self.team_id,channel_id=channel_id,name=payload.validated_data["name"],+ kind=payload.validated_data["kind"],+ description=payload.validated_data["description"],template_id=payload.validated_data["template_id"],created_by=user,# A sandbox-created canvas is its task's deliverable: bind@@ -300,6 +338,7 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):self._report_canvas_action("canvas created",canvas,+ kind=canvas.kind,template_id=canvas.template_id,is_sandbox_created=canvas.generation_task_id is not None,)@@ -334,6 +373,11 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):record("context")canvas.context = data["context"]update_fields.append("context")+ if "description" in data:+ if data["description"] != canvas.description:+ record("description", canvas.description, data["description"])+ canvas.description = data["description"]+ update_fields.append("description")if "pinned" in data:was_pinned = canvas.pinned_at is not Noneif data["pinned"] != was_pinned:@@ -442,10 +486,10 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):@action(methods=["POST"], detail=True)def validate(self, request: Request, *args: Any, **kwargs: Any) -> Response:"""Validate a candidate source project without publishing it. Side-effect free."""- self.get_object()+ canvas = self.get_object()payload = CanvasValidateRequestSerializer(data=request.data)payload.is_valid(raise_exception=True)- diagnostics = validate_source_project(payload.validated_data["project"])+ diagnostics = validate_source_project(payload.validated_data["project"], kind=canvas.kind)return Response({"valid": not has_errors(diagnostics), "diagnostics": diagnostics})@extend_schema(@@ -464,6 +508,9 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):def publish_current_version(self, request: Request, *args: Any, **kwargs: Any) -> Response:"""Queue a build for the current source version without changing source or metadata."""canvas = self.get_object()+ rejection = _grid_rejection(canvas)+ if rejection is not None:+ return rejectionpayload = CanvasPublishCurrentVersionSerializer(data=request.data)payload.is_valid(raise_exception=True)try:@@ -511,6 +558,9 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):A successful publish queues a server-side build."""canvas = self.get_object()+ rejection = _grid_rejection(canvas)+ if rejection is not None:+ return rejectionpayload = CanvasSourcePublishSerializer(data=request.data)payload.is_valid(raise_exception=True)return self._publish(@@ -550,6 +600,9 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):someone else's newer work."""canvas = self.get_object()+ rejection = _grid_rejection(canvas)+ if rejection is not None:+ return rejectionpayload = CanvasSourceEditSerializer(data=request.data)payload.is_valid(raise_exception=True)@@ -592,7 +645,7 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):has_expected_version: bool,expected_version_id: str | None,) -> Response:- diagnostics = validate_source_project(project)+ diagnostics = validate_source_project(project, kind=canvas.kind)if has_errors(diagnostics):return _invalid_response(diagnostics)@@ -712,10 +765,13 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):No version guard applies: a draft conflicts with nothing."""canvas = self.get_object()+ rejection = _grid_rejection(canvas)+ if rejection is not None:+ return rejectionpayload = CanvasSourceDraftSerializer(data=request.data)payload.is_valid(raise_exception=True)project = payload.validated_data["project"]- diagnostics = validate_source_project(project)+ diagnostics = validate_source_project(project, kind=canvas.kind)if has_errors(diagnostics):return _invalid_response(diagnostics)task_id = self._sandbox_task_id(request)diff --git a/products/canvas/backend/source.py b/products/canvas/backend/source.pyindex b1778c75c873..0d84f7387eee 100644--- a/products/canvas/backend/source.py+++ b/products/canvas/backend/source.py@@ -14,8 +14,12 @@ import reimport jsonfrom typing import Any+import jsonschema+from products.canvas.backend.actions import CANVAS_ACTIONSfrom products.canvas.backend.contract import (+ MAX_COMPONENT_HEIGHT,+ MAX_COMPONENT_WIDTH,allowed_import_specifiers,canonical_network_origin,canvas_sdk_version,@@ -28,6 +32,38 @@ CANVAS_ENTRY_HTML = "index.html"# The conventional React entry component (also what the synthetic shell mounts).CANVAS_COMPONENT_PATH = "src/canvas.tsx"+# Config schemas are author-supplied, so the vocabulary is an allowlist:+# no $ref/$dynamicRef (nothing downstream may be induced to resolve one) and+# no pattern/patternProperties (placement-config validation must not evaluate+# author-supplied regexes). Size-capped so a schema cannot bloat version rows.+MAX_CONFIG_SCHEMA_BYTES = 16 * 1024+# Depth-capped as well: a schema well under the byte cap can still nest deeply+# enough to exhaust the Python recursion limit inside jsonschema's check_schema+# (or our own keyword scan), which would escape as a 500 rather than a validation+# diagnostic. Bounded far below where check_schema starts recursing off the limit.+MAX_CONFIG_SCHEMA_DEPTH = 32+ALLOWED_CONFIG_SCHEMA_KEYWORDS = frozenset(+ {+ "type",+ "title",+ "description",+ "default",+ "properties",+ "required",+ "additionalProperties",+ "items",+ "enum",+ "const",+ "minimum",+ "maximum",+ "minLength",+ "maxLength",+ "minItems",+ "maxItems",+ "format",+ }+)+# File extensions whose content is scanned as source code._CODE_EXTENSIONS = (".ts", ".tsx", ".js", ".jsx")@@ -385,16 +421,137 @@ def _validate_capabilities(path: str, code: str, capabilities: dict[str, Any]) -return diagnostics-def validate_source_project(project: dict[str, Any]) -> list[dict[str, Any]]:+def _validate_component_size(size: Any) -> str | None:+ """Validate a component's grid-size contract; returns the problem or None."""+ if not isinstance(size, dict):+ return "component.size must be an object with defaultW, defaultH, minW, and minH"+ for key in ("defaultW", "defaultH", "minW", "minH", "maxW", "maxH"):+ value = size.get(key)+ if value is None:+ if key in ("maxW", "maxH"):+ continue+ return f"component.size.{key} is required"+ if not isinstance(value, int) or isinstance(value, bool) or value < 1:+ return f"component.size.{key} must be a positive integer"+ for axis, cap in (("W", MAX_COMPONENT_WIDTH), ("H", MAX_COMPONENT_HEIGHT)):+ maximum = size.get(f"max{axis}", cap)+ if maximum > cap:+ return f"component.size.max{axis} may not exceed {cap}"+ if not size[f"min{axis}"] <= size[f"default{axis}"] <= maximum:+ return f"component.size must satisfy min{axis} <= default{axis} <= max{axis} (cap {cap})"+ return None+++def _unknown_config_schema_keywords(schema: Any) -> set[str]:+ """Every schema keyword used anywhere in the schema tree that is not allowlisted."""+ if not isinstance(schema, dict):+ return set()+ unknown = {key for key in schema if key not in ALLOWED_CONFIG_SCHEMA_KEYWORDS}+ for key, value in schema.items():+ if key == "properties" and isinstance(value, dict):+ for nested in value.values():+ unknown |= _unknown_config_schema_keywords(nested)+ elif key in ("items", "additionalProperties"):+ unknown |= _unknown_config_schema_keywords(value)+ return unknown+++def _max_json_depth(value: Any) -> int:+ """Deepest container nesting in a JSON value, walked with an explicit stack.++ Author config schemas are hostile input, so depth is measured without+ recursion — the point is to bound nesting before any recursive processing+ (the keyword scan, jsonschema's check_schema) descends into it.+ """+ max_depth = 0+ stack: list[tuple[Any, int]] = [(value, 1)]+ while stack:+ current, depth = stack.pop()+ if isinstance(current, dict):+ children: Any = current.values()+ elif isinstance(current, list):+ children = current+ else:+ continue+ if depth > max_depth:+ max_depth = depth+ for child in children:+ stack.append((child, depth + 1))+ return max_depth+++def _validate_config_schema(config_schema: Any) -> str | None:+ """Validate a component's placement-config schema; returns the problem or None."""+ if not isinstance(config_schema, dict) or config_schema.get("type") != "object":+ return 'component.configSchema must be a JSON Schema object with "type": "object"'+ if len(json.dumps(config_schema, separators=(",", ":")).encode("utf-8")) > MAX_CONFIG_SCHEMA_BYTES:+ return f"component.configSchema may not exceed {MAX_CONFIG_SCHEMA_BYTES // 1024} KB serialized"+ if _max_json_depth(config_schema) > MAX_CONFIG_SCHEMA_DEPTH:+ return f"component.configSchema may not nest deeper than {MAX_CONFIG_SCHEMA_DEPTH} levels"+ unknown = _unknown_config_schema_keywords(config_schema)+ if unknown:+ return (+ "component.configSchema uses unsupported keywords: "+ + ", ".join(sorted(unknown))+ + " — supported: "+ + ", ".join(sorted(ALLOWED_CONFIG_SCHEMA_KEYWORDS))+ )+ try:+ jsonschema.Draft202012Validator.check_schema(config_schema)+ except jsonschema.SchemaError as error:+ return f"component.configSchema is not a valid JSON Schema: {error.message}"+ return None+++def validate_component_meta(project: dict[str, Any], kind: str) -> list[dict[str, Any]]:+ """Validate a project's component placement contract for its canvas kind.++ Components must declare how grids may place them (size, optional config+ schema); every other kind must not carry a contract, so an author cannot+ believe a freeform canvas is placeable.+ """+ meta = project.get("component")+ if kind != "component":+ if meta:+ return [+ diagnostic(+ "error",+ "component_meta_not_allowed",+ "only component-kind canvases may declare a `component` placement contract",+ )+ ]+ return []+ if not isinstance(meta, dict):+ return [+ diagnostic(+ "error",+ "component_meta_missing",+ "a component project must declare `component` with a `size` contract "+ '(e.g. {"size": {"defaultW": 2, "defaultH": 1, "minW": 1, "minH": 1}})',+ )+ ]+ diagnostics: list[dict[str, Any]] = []+ size_problem = _validate_component_size(meta.get("size"))+ if size_problem is not None:+ diagnostics.append(diagnostic("error", "component_size_invalid", size_problem))+ if meta.get("configSchema") is not None:+ schema_problem = _validate_config_schema(meta["configSchema"])+ if schema_problem is not None:+ diagnostics.append(diagnostic("error", "component_config_schema_invalid", schema_problem))+ return diagnostics+++def validate_source_project(project: dict[str, Any], *, kind: str = "freeform") -> list[dict[str, Any]]:"""Validate a candidate source project against the platform contract.Returns structured diagnostics; an empty list (or warnings only) means theproject is publishable. Mirrors the build pipeline's stage-1 validation(schema, paths, file count, total size) plus dependency, runtime-safety,and capability constraints. The authoritative builder performs- module-graph validation.+ module-graph validation. ``kind`` is the owning canvas's kind — it gates+ the component placement contract, which only component projects carry."""- diagnostics: list[dict[str, Any]] = []+ diagnostics: list[dict[str, Any]] = list(validate_component_meta(project, kind))limits = contract_limits()if project.get("schemaVersion") != CANVAS_SOURCE_SCHEMA_VERSION:diff --git a/products/canvas/backend/tests/test_component_store.py b/products/canvas/backend/tests/test_component_store.pynew file mode 100644index 000000000000..8ff85a78e2cb--- /dev/null+++ b/products/canvas/backend/tests/test_component_store.py@@ -0,0 +1,88 @@+from typing import Any++from parameterized import parameterized+from rest_framework import status++from posthog.models.scoping import team_scope++from products.canvas.backend.models import Canvas, CanvasSourceVersion+from products.canvas.backend.tests.test_canvas_api import CanvasAPIBaseTest++COMPONENT_META: dict[str, Any] = {+ "size": {"defaultW": 2, "defaultH": 1, "minW": 1, "minH": 1},+ "configSchema": {"type": "object", "properties": {"location": {"type": "string"}}},+}+++class TestComponentStore(CanvasAPIBaseTest):+ def _component_project(self, **overrides) -> dict[str, Any]:+ return self._project(component=COMPONENT_META, **overrides)++ def test_component_publish_requires_meta(self):+ canvas_id = self._create_canvas(kind="component")+ response = self._publish(canvas_id)+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert response.json()["code"] == "invalid_source_project"+ assert any(entry["code"] == "component_meta_missing" for entry in response.json()["diagnostics"])++ def test_component_publish_snapshots_meta_and_lists_it(self):+ canvas_id = self._create_canvas(kind="component", description="Local weather tile")+ response = self._publish(canvas_id, self._component_project())+ assert response.status_code == status.HTTP_200_OK, response.json()+ with team_scope(self.team.id):+ version = CanvasSourceVersion.objects.get(pk=response.json()["current_version_id"])+ assert version.component_meta == COMPONENT_META++ listed = self.client.get(f"/api/projects/{self.team.id}/canvases/?kind=component")+ rows = listed.json()["results"]+ assert [row["id"] for row in rows] == [canvas_id]+ assert rows[0]["kind"] == "component"+ assert rows[0]["description"] == "Local weather tile"+ assert rows[0]["component_meta"] == COMPONENT_META++ def test_freeform_publish_rejects_component_meta(self):+ canvas_id = self._create_canvas()+ response = self._publish(canvas_id, self._component_project())+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert any(entry["code"] == "component_meta_not_allowed" for entry in response.json()["diagnostics"])++ @parameterized.expand(["publish", "edit", "draft", "publish-current-version"])+ def test_grid_canvas_rejects_source_endpoints(self, endpoint: str):+ canvas_id = self._create_canvas(kind="grid")+ response = self.client.post(+ f"/api/projects/{self.team.id}/canvases/{canvas_id}/{endpoint}/",+ {"project": self._project(), "operations": [{"path": "src/canvas.tsx", "content": "x"}]},+ format="json",+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert response.json()["code"] == "wrong_canvas_kind"++ def test_list_filters_by_kind_and_search(self):+ self._create_canvas(name="Plain app")+ weather_id = self._create_canvas(kind="component", name="Weather", description="Shows local weather")+ self._create_canvas(kind="component", name="Kanban", description="Task board")++ by_kind = self.client.get(f"/api/projects/{self.team.id}/canvases/?kind=component")+ assert {row["name"] for row in by_kind.json()["results"]} == {"Weather", "Kanban"}++ by_search = self.client.get(f"/api/projects/{self.team.id}/canvases/?kind=component&search=weather")+ assert [row["id"] for row in by_search.json()["results"]] == [weather_id]++ def test_create_rejects_unknown_kind(self):+ response = self.client.post(+ f"/api/projects/{self.team.id}/canvases/",+ {"name": "Bad", "channel_id": str(self.channel.id), "kind": "widget"},+ format="json",+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST++ def test_update_description(self):+ canvas_id = self._create_canvas(kind="component")+ response = self.client.patch(+ f"/api/projects/{self.team.id}/canvases/{canvas_id}/",+ {"description": "Shows the local weather for a configured location"},+ format="json",+ )+ assert response.status_code == status.HTTP_200_OK+ with team_scope(self.team.id):+ assert Canvas.objects.get(pk=canvas_id).description == "Shows the local weather for a configured location"diff --git a/products/canvas/backend/tests/test_source.py b/products/canvas/backend/tests/test_source.pyindex 7901ad138494..bc028917fbd1 100644--- a/products/canvas/backend/tests/test_source.py+++ b/products/canvas/backend/tests/test_source.py@@ -1,3 +1,5 @@+from typing import Any+from django.test import SimpleTestCasefrom parameterized import parameterized@@ -6,6 +8,7 @@ from products.canvas.backend.contract import contract_limitsfrom products.canvas.backend.source import (CANVAS_COMPONENT_PATH,CANVAS_ENTRY_HTML,+ MAX_CONFIG_SCHEMA_DEPTH,has_errors,synthetic_source_project,validate_source_project,@@ -264,3 +267,93 @@ class TestCanvasSourceAdapter(SimpleTestCase):diagnostics = validate_source_project(candidate)self.assertIn("capability_missing_agent_requests", [entry["code"] for entry in diagnostics])+++def component_meta(**overrides):+ meta = {+ "size": {"defaultW": 2, "defaultH": 1, "minW": 1, "minH": 1},+ "configSchema": {"type": "object", "properties": {"location": {"type": "string"}}},+ }+ meta.update(overrides)+ return meta+++def deeply_nested_config_schema(levels):+ schema: dict[str, Any] = {"type": "object"}+ for _ in range(levels):+ schema = {"type": "object", "items": schema}+ return schema+++class TestComponentMetaValidation(SimpleTestCase):+ def test_valid_component_project_has_no_errors(self):+ candidate = project(component=component_meta())+ self.assertFalse(has_errors(validate_source_project(candidate, kind="component")))++ def test_component_meta_is_rejected_outside_component_kind(self):+ diagnostics = validate_source_project(project(component=component_meta()))+ self.assertIn("component_meta_not_allowed", [entry["code"] for entry in diagnostics])++ @parameterized.expand(+ [+ ("missing_meta", None, "component_meta_missing"),+ ("meta_not_object", "big", "component_meta_missing"),+ ("missing_size", {"configSchema": {"type": "object"}}, "component_size_invalid"),+ (+ "size_not_ints",+ component_meta(size={"defaultW": "2", "defaultH": 1, "minW": 1, "minH": 1}),+ "component_size_invalid",+ ),+ (+ "min_above_default",+ component_meta(size={"defaultW": 1, "defaultH": 1, "minW": 2, "minH": 1}),+ "component_size_invalid",+ ),+ (+ "default_above_max",+ component_meta(size={"defaultW": 4, "defaultH": 1, "minW": 1, "minH": 1, "maxW": 3}),+ "component_size_invalid",+ ),+ (+ "width_above_grid_cap",+ component_meta(size={"defaultW": 13, "defaultH": 1, "minW": 1, "minH": 1}),+ "component_size_invalid",+ ),+ (+ "zero_height",+ component_meta(size={"defaultW": 1, "defaultH": 0, "minW": 1, "minH": 0}),+ "component_size_invalid",+ ),+ (+ "config_schema_not_object_type",+ component_meta(configSchema={"type": "array"}),+ "component_config_schema_invalid",+ ),+ (+ "config_schema_malformed",+ component_meta(configSchema={"type": "object", "properties": 5}),+ "component_config_schema_invalid",+ ),+ (+ "config_schema_ref_not_allowlisted",+ component_meta(configSchema={"type": "object", "properties": {"a": {"$ref": "#/defs/a"}}}),+ "component_config_schema_invalid",+ ),+ (+ "config_schema_pattern_not_allowlisted",+ component_meta(+ configSchema={"type": "object", "properties": {"a": {"type": "string", "pattern": "^a"}}}+ ),+ "component_config_schema_invalid",+ ),+ (+ "config_schema_too_deeply_nested",+ component_meta(configSchema=deeply_nested_config_schema(MAX_CONFIG_SCHEMA_DEPTH + 200)),+ "component_config_schema_invalid",+ ),+ ]+ )+ def test_invalid_component_meta_produces_error(self, _name, meta, expected_code):+ candidate = project() if meta is None else project(component=meta)+ diagnostics = validate_source_project(candidate, kind="component")+ self.assertIn(expected_code, [entry["code"] for entry in diagnostics])diff --git a/products/canvas/frontend/generated/api.schemas.ts b/products/canvas/frontend/generated/api.schemas.tsindex da11522b4c2f..4945ea76f320 100644--- a/products/canvas/frontend/generated/api.schemas.ts+++ b/products/canvas/frontend/generated/api.schemas.ts@@ -7,6 +7,76 @@* PostHog API - generated* OpenAPI spec version: 1.0.0*/+/**+ * * `freeform` - freeform+ * * `grid` - grid+ * * `component` - component+ */+export type CanvasKindEnumApi = (typeof CanvasKindEnumApi)[keyof typeof CanvasKindEnumApi]++export const CanvasKindEnumApi = {+ Freeform: 'freeform',+ Grid: 'grid',+ Component: 'component',+} as const++/**+ * A component's grid-size contract, in grid units.+ */+export interface CanvasComponentSizeApi {+ /**+ * Width a new placement starts at, in grid columns.+ * @minimum 1+ * @maximum 12+ */+ defaultW: number+ /**+ * Height a new placement starts at, in grid rows.+ * @minimum 1+ * @maximum 40+ */+ defaultH: number+ /**+ * Narrowest width the component renders usefully at.+ * @minimum 1+ * @maximum 12+ */+ minW: number+ /**+ * Shortest height the component renders usefully at.+ * @minimum 1+ * @maximum 40+ */+ minH: number+ /**+ * Widest allowed width; omit for no cap below the grid's width.+ * @minimum 1+ * @maximum 12+ */+ maxW?: number+ /**+ * Tallest allowed height; omit for no cap.+ * @minimum 1+ * @maximum 40+ */+ maxH?: number+}++/**+ * JSON Schema ("type": "object") for a placement's config. The host validates each placement's config against it and passes the validated object to the widget at mount.+ */+export type CanvasComponentMetaApiConfigSchema = { [key: string]: unknown }++/**+ * A component's placement contract: how grid canvases may place and configure it.+ */+export interface CanvasComponentMetaApi {+ /** Grid-size contract for placements of this component. */+ size: CanvasComponentSizeApi+ /** JSON Schema ("type": "object") for a placement's config. The host validates each placement's config against it and passes the validated object to the widget at mount. */+ configSchema?: CanvasComponentMetaApiConfigSchema+}+/*** * `engineering` - Engineering* * `data` - Data@@ -70,6 +140,14 @@ export interface UserBasicApi {export interface CanvasApi {readonly id: stringreadonly name: string+ /** What the canvas is: 'freeform' (a standalone app), 'component' (a reusable widget grids place), or 'grid' (a composition of components).+ *+ * * `freeform` - freeform+ * * `grid` - grid+ * * `component` - component */+ readonly kind: CanvasKindEnumApi+ /** Short prose describing the canvas. For components, the store-search text. */+ readonly description: stringreadonly channel: stringreadonly template_id: stringreadonly context: string@@ -89,6 +167,8 @@ export interface CanvasApi {* @nullable*/readonly published_build_id: string | null+ /** For component-kind canvases: the head version's placement contract (size, optional configSchema). Null for other kinds and unpublished components. */+ readonly component_meta: CanvasComponentMetaApi | nullreadonly created_by: UserBasicApireadonly created_at: stringreadonly updated_at: string@@ -116,6 +196,14 @@ export interface CanvasCreateApi {name: string/** Id of the channel the canvas belongs to. */channel_id: string+ /** What to create: 'freeform' (a standalone app), 'component' (a reusable widget for grids — its published project must declare a `component` placement contract), or 'grid' (a composition of components, edited through the layout endpoints).+ *+ * * `freeform` - freeform+ * * `grid` - grid+ * * `component` - component */+ kind?: CanvasKindEnumApi+ /** Short prose describing the canvas. For components this is the store-search text agents match against — say what the widget shows and what its config controls. */+ description?: string/*** Canvas template identifier.* @maxLength 64@@ -134,6 +222,8 @@ export interface PatchedCanvasUpdateApi {name?: string/** Updated author context markdown. */context?: string+ /** Updated canvas description (for components, the store-search text). */+ description?: string/** Whether the canvas is pinned in its channel. */pinned?: boolean/**@@ -243,6 +333,12 @@ export type CanvasArtifactManifestApiDependencies = { [key: string]: string }*/export type CanvasArtifactManifestApiCapabilities = { [key: string]: unknown }+/**+ * For component artifacts: the placement contract (size, configSchema) frozen into the build.+ * @nullable+ */+export type CanvasArtifactManifestApiComponent = { [key: string]: unknown } | null+/*** The manifest frozen into a ready build: entry, assets, versions, capabilities.*/@@ -267,6 +363,11 @@ export interface CanvasArtifactManifestApi {legacyCode?: string | null/** Declared PostHog/network capabilities the artifact is held to at runtime. */capabilities: CanvasArtifactManifestApiCapabilities+ /**+ * For component artifacts: the placement contract (size, configSchema) frozen into the build.+ * @nullable+ */+ component?: CanvasArtifactManifestApiComponent}/**@@ -473,6 +574,8 @@ export interface CanvasSourceProjectApi {dependencies?: CanvasSourceProjectApiDependencies/** Version of the host-injected `ph` canvas SDK the project targets. */canvasSdkVersion?: string+ /** Placement contract, required for (and only allowed on) component-kind canvases: the grid size the component takes and the JSON Schema of its per-placement config. */+ component?: CanvasComponentMetaApi/** Bounded capabilities frozen into the built artifact. Declare every insight short id the canvas loads, every event it captures, and inlineQueries when it runs ad-hoc HogQL — the host enforces these at runtime and validation rejects undeclared `ph` calls. Network origins must be exact HTTPS origins. Data fetched by canvas code can be sent to those origins. */capabilities?: CanvasCapabilitiesApi}@@ -616,6 +719,12 @@ export interface CanvasSummaryApi {id: string/** Display name of the canvas. */name: string+ /** The canvas's kind (freeform, component, or grid).+ *+ * * `freeform` - freeform+ * * `grid` - grid+ * * `component` - component */+ kind: CanvasKindEnumApi/** Id of the channel the canvas belongs to. */channel_id: string/**@@ -978,6 +1087,10 @@ export type CanvasesListParams = {* Only return canvases in this channel.*/channel?: string+ /**+ * Only return canvases of this kind. kind=component lists the component store.+ */+ kind?: CanvasesListKind/*** Number of results to return per page.*/@@ -986,8 +1099,20 @@ export type CanvasesListParams = {* The initial index from which to return the results.*/offset?: number+ /**+ * Only return canvases whose name or description contains this text (case-insensitive).+ */+ search?: string}+export type CanvasesListKind = (typeof CanvasesListKind)[keyof typeof CanvasesListKind]++export const CanvasesListKind = {+ Component: 'component',+ Freeform: 'freeform',+ Grid: 'grid',+} as const+export type CanvasesBuildsRetrieveParams = {/*** Include the retained ready build for this historical source version.diff --git a/products/canvas/frontend/generated/api.zod.ts b/products/canvas/frontend/generated/api.zod.tsindex 7821e1e5f8a3..9f74eb6d6ea5 100644--- a/products/canvas/frontend/generated/api.zod.ts+++ b/products/canvas/frontend/generated/api.zod.ts@@ -14,6 +14,8 @@ import * as zod from 'zod'*/export const canvasesCreateBodyNameMax = 400+export const canvasesCreateBodyKindDefault = `freeform`+export const canvasesCreateBodyDescriptionDefault = ``export const canvasesCreateBodyTemplateIdDefault = `freeform`export const canvasesCreateBodyTemplateIdMax = 64@@ -21,6 +23,19 @@ export const CanvasesCreateBody = /* @__PURE__ */ zod.object({name: zod.string().max(canvasesCreateBodyNameMax).describe('Display name for the canvas.'),channel_id: zod.uuid().describe('Id of the channel the canvas belongs to.'),+ kind: zod+ .enum(['freeform', 'grid', 'component'])+ .describe('\* `freeform` - freeform\n\* `grid` - grid\n\* `component` - component')+ .default(canvasesCreateBodyKindDefault)+ .describe(+ "What to create: 'freeform' (a standalone app), 'component' (a reusable widget for grids — its published project must declare a `component` placement contract), or 'grid' (a composition of components, edited through the layout endpoints).\n\n\* `freeform` - freeform\n\* `grid` - grid\n\* `component` - component"+ ),+ description: zod+ .string()+ .default(canvasesCreateBodyDescriptionDefault)+ .describe(+ 'Short prose describing the canvas. For components this is the store-search text agents match against — say what the widget shows and what its config controls.'+ ),template_id: zod.string().max(canvasesCreateBodyTemplateIdMax)@@ -38,6 +53,10 @@ export const CanvasesPartialUpdateBody = /* @__PURE__ */ zod.object({name: zod.string().max(canvasesPartialUpdateBodyNameMax).optional().describe('Updated display name.'),context: zod.string().optional().describe('Updated author context markdown.'),+ description: zod+ .string()+ .optional()+ .describe('Updated canvas description (for components, the store-search text).'),pinned: zod.boolean().optional().describe('Whether the canvas is pinned in its channel.'),generation_task_id: zod.uuid()@@ -93,6 +112,18 @@ export const canvasesDraftCreateBodyProjectOneAssetsContentMax = 2796204export const canvasesDraftCreateBodyProjectOneAssetsContentRegExp = new RegExp('^(?:[A-Za-z0-9+\/]{4})\*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$')+export const canvasesDraftCreateBodyProjectOneComponentOneSizeOneDefaultWMax = 12++export const canvasesDraftCreateBodyProjectOneComponentOneSizeOneDefaultHMax = 40++export const canvasesDraftCreateBodyProjectOneComponentOneSizeOneMinWMax = 12++export const canvasesDraftCreateBodyProjectOneComponentOneSizeOneMinHMax = 40++export const canvasesDraftCreateBodyProjectOneComponentOneSizeOneMaxWMax = 12++export const canvasesDraftCreateBodyProjectOneComponentOneSizeOneMaxHMax = 40+export const canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogInsightsItemMax = 128export const canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogInsightsMax = 100@@ -159,6 +190,57 @@ export const CanvasesDraftCreateBody = /* @__PURE__ */ zod.string().optional().describe('Version of the host-injected `ph` canvas SDK the project targets.'),+ component: zod+ .object({+ size: zod+ .object({+ defaultW: zod+ .number()+ .min(1)+ .max(canvasesDraftCreateBodyProjectOneComponentOneSizeOneDefaultWMax)+ .describe('Width a new placement starts at, in grid columns.'),+ defaultH: zod+ .number()+ .min(1)+ .max(canvasesDraftCreateBodyProjectOneComponentOneSizeOneDefaultHMax)+ .describe('Height a new placement starts at, in grid rows.'),+ minW: zod+ .number()+ .min(1)+ .max(canvasesDraftCreateBodyProjectOneComponentOneSizeOneMinWMax)+ .describe('Narrowest width the component renders usefully at.'),+ minH: zod+ .number()+ .min(1)+ .max(canvasesDraftCreateBodyProjectOneComponentOneSizeOneMinHMax)+ .describe('Shortest height the component renders usefully at.'),+ maxW: zod+ .number()+ .min(1)+ .max(canvasesDraftCreateBodyProjectOneComponentOneSizeOneMaxWMax)+ .optional()+ .describe("Widest allowed width; omit for no cap below the grid's width."),+ maxH: zod+ .number()+ .min(1)+ .max(canvasesDraftCreateBodyProjectOneComponentOneSizeOneMaxHMax)+ .optional()+ .describe('Tallest allowed height; omit for no cap.'),+ })+ .describe("A component's grid-size contract, in grid units.")+ .describe('Grid-size contract for placements of this component.'),+ configSchema: zod+ .record(zod.string(), zod.unknown())+ .optional()+ .describe(+ 'JSON Schema (\"type\": \"object\") for a placement\'s config. The host validates each placement\'s config against it and passes the validated object to the widget at mount.'+ ),+ })+ .describe("A component's placement contract: how grid canvases may place and configure it.")+ .optional()+ .describe(+ 'Placement contract, required for (and only allowed on) component-kind canvases: the grid size the component takes and the JSON Schema of its per-placement config.'+ ),capabilities: zod.object({posthog: zod.object({@@ -301,6 +383,18 @@ export const canvasesPublishCreateBodyProjectOneAssetsContentMax = 2796204export const canvasesPublishCreateBodyProjectOneAssetsContentRegExp = new RegExp('^(?:[A-Za-z0-9+\/]{4})\*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$')+export const canvasesPublishCreateBodyProjectOneComponentOneSizeOneDefaultWMax = 12++export const canvasesPublishCreateBodyProjectOneComponentOneSizeOneDefaultHMax = 40++export const canvasesPublishCreateBodyProjectOneComponentOneSizeOneMinWMax = 12++export const canvasesPublishCreateBodyProjectOneComponentOneSizeOneMinHMax = 40++export const canvasesPublishCreateBodyProjectOneComponentOneSizeOneMaxWMax = 12++export const canvasesPublishCreateBodyProjectOneComponentOneSizeOneMaxHMax = 40+export const canvasesPublishCreateBodyProjectOneCapabilitiesOnePosthogInsightsItemMax = 128export const canvasesPublishCreateBodyProjectOneCapabilitiesOnePosthogInsightsMax = 100@@ -369,6 +463,57 @@ export const CanvasesPublishCreateBody = /* @__PURE__ */ zod.string().optional().describe('Version of the host-injected `ph` canvas SDK the project targets.'),+ component: zod+ .object({+ size: zod+ .object({+ defaultW: zod+ .number()+ .min(1)+ .max(canvasesPublishCreateBodyProjectOneComponentOneSizeOneDefaultWMax)+ .describe('Width a new placement starts at, in grid columns.'),+ defaultH: zod+ .number()+ .min(1)+ .max(canvasesPublishCreateBodyProjectOneComponentOneSizeOneDefaultHMax)+ .describe('Height a new placement starts at, in grid rows.'),+ minW: zod+ .number()+ .min(1)+ .max(canvasesPublishCreateBodyProjectOneComponentOneSizeOneMinWMax)+ .describe('Narrowest width the component renders usefully at.'),+ minH: zod+ .number()+ .min(1)+ .max(canvasesPublishCreateBodyProjectOneComponentOneSizeOneMinHMax)+ .describe('Shortest height the component renders usefully at.'),+ maxW: zod+ .number()+ .min(1)+ .max(canvasesPublishCreateBodyProjectOneComponentOneSizeOneMaxWMax)+ .optional()+ .describe("Widest allowed width; omit for no cap below the grid's width."),+ maxH: zod+ .number()+ .min(1)+ .max(canvasesPublishCreateBodyProjectOneComponentOneSizeOneMaxHMax)+ .optional()+ .describe('Tallest allowed height; omit for no cap.'),+ })+ .describe("A component's grid-size contract, in grid units.")+ .describe('Grid-size contract for placements of this component.'),+ configSchema: zod+ .record(zod.string(), zod.unknown())+ .optional()+ .describe(+ 'JSON Schema (\"type\": \"object\") for a placement\'s config. The host validates each placement\'s config against it and passes the validated object to the widget at mount.'+ ),+ })+ .describe("A component's placement contract: how grid canvases may place and configure it.")+ .optional()+ .describe(+ 'Placement contract, required for (and only allowed on) component-kind canvases: the grid size the component takes and the JSON Schema of its per-placement config.'+ ),capabilities: zod.object({posthog: zod.object({@@ -555,6 +700,18 @@ export const canvasesValidateCreateBodyProjectOneAssetsContentMax = 2796204export const canvasesValidateCreateBodyProjectOneAssetsContentRegExp = new RegExp('^(?:[A-Za-z0-9+\/]{4})\*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$')+export const canvasesValidateCreateBodyProjectOneComponentOneSizeOneDefaultWMax = 12++export const canvasesValidateCreateBodyProjectOneComponentOneSizeOneDefaultHMax = 40++export const canvasesValidateCreateBodyProjectOneComponentOneSizeOneMinWMax = 12++export const canvasesValidateCreateBodyProjectOneComponentOneSizeOneMinHMax = 40++export const canvasesValidateCreateBodyProjectOneComponentOneSizeOneMaxWMax = 12++export const canvasesValidateCreateBodyProjectOneComponentOneSizeOneMaxHMax = 40+export const canvasesValidateCreateBodyProjectOneCapabilitiesOnePosthogInsightsItemMax = 128export const canvasesValidateCreateBodyProjectOneCapabilitiesOnePosthogInsightsMax = 100@@ -621,6 +778,57 @@ export const CanvasesValidateCreateBody = /* @__PURE__ */ zod.string().optional().describe('Version of the host-injected `ph` canvas SDK the project targets.'),+ component: zod+ .object({+ size: zod+ .object({+ defaultW: zod+ .number()+ .min(1)+ .max(canvasesValidateCreateBodyProjectOneComponentOneSizeOneDefaultWMax)+ .describe('Width a new placement starts at, in grid columns.'),+ defaultH: zod+ .number()+ .min(1)+ .max(canvasesValidateCreateBodyProjectOneComponentOneSizeOneDefaultHMax)+ .describe('Height a new placement starts at, in grid rows.'),+ minW: zod+ .number()+ .min(1)+ .max(canvasesValidateCreateBodyProjectOneComponentOneSizeOneMinWMax)+ .describe('Narrowest width the component renders usefully at.'),+ minH: zod+ .number()+ .min(1)+ .max(canvasesValidateCreateBodyProjectOneComponentOneSizeOneMinHMax)+ .describe('Shortest height the component renders usefully at.'),+ maxW: zod+ .number()+ .min(1)+ .max(canvasesValidateCreateBodyProjectOneComponentOneSizeOneMaxWMax)+ .optional()+ .describe("Widest allowed width; omit for no cap below the grid's width."),+ maxH: zod+ .number()+ .min(1)+ .max(canvasesValidateCreateBodyProjectOneComponentOneSizeOneMaxHMax)+ .optional()+ .describe('Tallest allowed height; omit for no cap.'),+ })+ .describe("A component's grid-size contract, in grid units.")+ .describe('Grid-size contract for placements of this component.'),+ configSchema: zod+ .record(zod.string(), zod.unknown())+ .optional()+ .describe(+ 'JSON Schema (\"type\": \"object\") for a placement\'s config. The host validates each placement\'s config against it and passes the validated object to the widget at mount.'+ ),+ })+ .describe("A component's placement contract: how grid canvases may place and configure it.")+ .optional()+ .describe(+ 'Placement contract, required for (and only allowed on) component-kind canvases: the grid size the component takes and the JSON Schema of its per-placement config.'+ ),capabilities: zod.object({posthog: zod.object({diff --git a/products/canvas/packages/canvas_builder/build.mjs b/products/canvas/packages/canvas_builder/build.mjsindex 7bddbb121de8..44338b648b1e 100644--- a/products/canvas/packages/canvas_builder/build.mjs+++ b/products/canvas/packages/canvas_builder/build.mjs@@ -547,6 +547,10 @@ async function buildCanvas(project) {posthog: { insights: [], inlineQueries: false, captureEvents: [] },network: { origins: [] },},+ // Component-kind canvases freeze their placement contract (size,+ // config schema) into the artifact, like capabilities: the grid host+ // holds a placed widget to the contract its build shipped with.+ ...(project.component ? { component: project.component } : {}),...legacy,}return { contractVersion: 1, status: 'ready', diagnostics: [], manifest, files }diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 1b5a1c0c714d..68bbc4f328c1 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -14787,12 +14787,91 @@ export namespace Schemas {created: string | null;}+ /**+ * * `freeform` - freeform+ * * `grid` - grid+ * * `component` - component+ */+ export type CanvasKindEnum = typeof CanvasKindEnum[keyof typeof CanvasKindEnum];+++ export const CanvasKindEnum = {+ Freeform: 'freeform',+ Grid: 'grid',+ Component: 'component',+ } as const;++ /**+ * A component's grid-size contract, in grid units.+ */+ export interface CanvasComponentSize {+ /**+ * Width a new placement starts at, in grid columns.+ * @minimum 1+ * @maximum 12+ */+ defaultW: number;+ /**+ * Height a new placement starts at, in grid rows.+ * @minimum 1+ * @maximum 40+ */+ defaultH: number;+ /**+ * Narrowest width the component renders usefully at.+ * @minimum 1+ * @maximum 12+ */+ minW: number;+ /**+ * Shortest height the component renders usefully at.+ * @minimum 1+ * @maximum 40+ */+ minH: number;+ /**+ * Widest allowed width; omit for no cap below the grid's width.+ * @minimum 1+ * @maximum 12+ */+ maxW?: number;+ /**+ * Tallest allowed height; omit for no cap.+ * @minimum 1+ * @maximum 40+ */+ maxH?: number;+ }++ /**+ * JSON Schema ("type": "object") for a placement's config. The host validates each placement's config against it and passes the validated object to the widget at mount.+ */+ export type CanvasComponentMetaConfigSchema = { [key: string]: unknown };++ /**+ * A component's placement contract: how grid canvases may place and configure it.+ */+ export interface CanvasComponentMeta {+ /** Grid-size contract for placements of this component. */+ size: CanvasComponentSize;+ /** JSON Schema ("type": "object") for a placement's config. The host validates each placement's config against it and passes the validated object to the widget at mount. */+ configSchema?: CanvasComponentMetaConfigSchema;+ }+/*** A canvas document. Version/build content hangs off the source and build endpoints.*/export interface Canvas {readonly id: string;readonly name: string;+ /** What the canvas is: 'freeform' (a standalone app), 'component' (a reusable widget grids place), or 'grid' (a composition of components).+ *+ * * `freeform` - freeform+ * * `grid` - grid+ * * `component` - component */+ readonly kind: CanvasKindEnum;+ /** Short prose describing the canvas. For components, the store-search text. */+ readonly description: string;readonly channel: string;readonly template_id: string;readonly context: string;@@ -14812,6 +14891,8 @@ export namespace Schemas {* @nullable*/readonly published_build_id: string | null;+ /** For component-kind canvases: the head version's placement contract (size, optional configSchema). Null for other kinds and unpublished components. */+ readonly component_meta: CanvasComponentMeta | null;readonly created_by: UserBasic;readonly created_at: string;readonly updated_at: string;@@ -14938,6 +15019,12 @@ export namespace Schemas {*/export type CanvasArtifactManifestCapabilities = { [key: string]: unknown };+ /**+ * For component artifacts: the placement contract (size, configSchema) frozen into the build.+ * @nullable+ */+ export type CanvasArtifactManifestComponent = { [key: string]: unknown } | null;+/*** The manifest frozen into a ready build: entry, assets, versions, capabilities.*/@@ -14962,6 +15049,11 @@ export namespace Schemas {legacyCode?: string | null;/** Declared PostHog/network capabilities the artifact is held to at runtime. */capabilities: CanvasArtifactManifestCapabilities;+ /**+ * For component artifacts: the placement contract (size, configSchema) frozen into the build.+ * @nullable+ */+ component?: CanvasArtifactManifestComponent;}/**@@ -15147,6 +15239,14 @@ export namespace Schemas {name: string;/** Id of the channel the canvas belongs to. */channel_id: string;+ /** What to create: 'freeform' (a standalone app), 'component' (a reusable widget for grids — its published project must declare a `component` placement contract), or 'grid' (a composition of components, edited through the layout endpoints).+ *+ * * `freeform` - freeform+ * * `grid` - grid+ * * `component` - component */+ kind?: CanvasKindEnum;+ /** Short prose describing the canvas. For components this is the store-search text agents match against — say what the widget shows and what its config controls. */+ description?: string;/*** Canvas template identifier.* @maxLength 64@@ -15390,6 +15490,8 @@ export namespace Schemas {dependencies?: CanvasSourceProjectDependencies;/** Version of the host-injected `ph` canvas SDK the project targets. */canvasSdkVersion?: string;+ /** Placement contract, required for (and only allowed on) component-kind canvases: the grid size the component takes and the JSON Schema of its per-placement config. */+ component?: CanvasComponentMeta;/** Bounded capabilities frozen into the built artifact. Declare every insight short id the canvas loads, every event it captures, and inlineQueries when it runs ad-hoc HogQL — the host enforces these at runtime and validation rejects undeclared `ph` calls. Network origins must be exact HTTPS origins. Data fetched by canvas code can be sent to those origins. */capabilities?: CanvasCapabilities;}@@ -15491,6 +15593,12 @@ export namespace Schemas {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;/**@@ -55907,6 +56015,8 @@ export namespace Schemas {name?: string;/** Updated author context markdown. */context?: string;+ /** Updated canvas description (for components, the store-search text). */+ description?: string;/** Whether the canvas is pinned in its channel. */pinned?: boolean;/**@@ -84538,6 +84648,10 @@ export namespace Schemas {* Only return canvases in this channel.*/channel?: string;+ /**+ * Only return canvases of this kind. kind=component lists the component store.+ */+ kind?: CanvasesListKind;/*** Number of results to return per page.*/@@ -84546,8 +84660,21 @@ export namespace Schemas {* The initial index from which to return the results.*/offset?: number;+ /**+ * Only return canvases whose name or description contains this text (case-insensitive).+ */+ search?: string;};+ export type CanvasesListKind = typeof CanvasesListKind[keyof typeof CanvasesListKind];+++ export const CanvasesListKind = {+ Component: 'component',+ Freeform: 'freeform',+ Grid: 'grid',+ } as const;+export type CanvasesBuildsRetrieveParams = {/*** Include the retained ready build for this historical source version.diff --git a/services/mcp/src/generated/canvas/api.ts b/services/mcp/src/generated/canvas/api.tsindex 6285f87cb0d6..e3a7e90cbdc3 100644--- a/services/mcp/src/generated/canvas/api.ts+++ b/services/mcp/src/generated/canvas/api.ts@@ -24,8 +24,16 @@ export const CanvasesListParams = /* @__PURE__ */ zod.object({export const CanvasesListQueryParams = /* @__PURE__ */ zod.object({channel: zod.string().optional().describe('Only return canvases in this channel.'),+ kind: zod+ .enum(['component', 'freeform', 'grid'])+ .optional()+ .describe('Only return canvases of this kind. kind=component lists the component store.'),limit: zod.number().optional().describe('Number of results to return per page.'),offset: zod.number().optional().describe('The initial index from which to return the results.'),+ search: zod+ .string()+ .optional()+ .describe('Only return canvases whose name or description contains this text (case-insensitive).'),})/**@@ -41,6 +49,8 @@ export const CanvasesCreateParams = /* @__PURE__ */ zod.object({export const canvasesCreateBodyNameMax = 400+export const canvasesCreateBodyKindDefault = `freeform`+export const canvasesCreateBodyDescriptionDefault = ``export const canvasesCreateBodyTemplateIdDefault = `freeform`export const canvasesCreateBodyTemplateIdMax = 64@@ -48,6 +58,19 @@ export const CanvasesCreateBody = /* @__PURE__ */ zod.object({name: zod.string().max(canvasesCreateBodyNameMax).describe('Display name for the canvas.'),channel_id: zod.string().describe('Id of the channel the canvas belongs to.'),+ kind: zod+ .enum(['freeform', 'grid', 'component'])+ .describe('\* `freeform` - freeform\n\* `grid` - grid\n\* `component` - component')+ .default(canvasesCreateBodyKindDefault)+ .describe(+ "What to create: 'freeform' (a standalone app), 'component' (a reusable widget for grids — its published project must declare a `component` placement contract), or 'grid' (a composition of components, edited through the layout endpoints).\n\n\* `freeform` - freeform\n\* `grid` - grid\n\* `component` - component"+ ),+ description: zod+ .string()+ .default(canvasesCreateBodyDescriptionDefault)+ .describe(+ 'Short prose describing the canvas. For components this is the store-search text agents match against — say what the widget shows and what its config controls.'+ ),template_id: zod.string().max(canvasesCreateBodyTemplateIdMax)@@ -103,6 +126,18 @@ export const canvasesDraftCreateBodyProjectOneAssetsContentMax = 2796204export const canvasesDraftCreateBodyProjectOneAssetsContentRegExp = new RegExp('^(?:[A-Za-z0-9+\/]{4})\*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$')+export const canvasesDraftCreateBodyProjectOneComponentOneSizeOneDefaultWMax = 12++export const canvasesDraftCreateBodyProjectOneComponentOneSizeOneDefaultHMax = 40++export const canvasesDraftCreateBodyProjectOneComponentOneSizeOneMinWMax = 12++export const canvasesDraftCreateBodyProjectOneComponentOneSizeOneMinHMax = 40++export const canvasesDraftCreateBodyProjectOneComponentOneSizeOneMaxWMax = 12++export const canvasesDraftCreateBodyProjectOneComponentOneSizeOneMaxHMax = 40+export const canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogInsightsItemMax = 128export const canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogInsightsMax = 100@@ -169,6 +204,57 @@ export const CanvasesDraftCreateBody = /* @__PURE__ */ zod.string().optional().describe('Version of the host-injected `ph` canvas SDK the project targets.'),+ component: zod+ .object({+ size: zod+ .object({+ defaultW: zod+ .number()+ .min(1)+ .max(canvasesDraftCreateBodyProjectOneComponentOneSizeOneDefaultWMax)+ .describe('Width a new placement starts at, in grid columns.'),+ defaultH: zod+ .number()+ .min(1)+ .max(canvasesDraftCreateBodyProjectOneComponentOneSizeOneDefaultHMax)+ .describe('Height a new placement starts at, in grid rows.'),+ minW: zod+ .number()+ .min(1)+ .max(canvasesDraftCreateBodyProjectOneComponentOneSizeOneMinWMax)+ .describe('Narrowest width the component renders usefully at.'),+ minH: zod+ .number()+ .min(1)+ .max(canvasesDraftCreateBodyProjectOneComponentOneSizeOneMinHMax)+ .describe('Shortest height the component renders usefully at.'),+ maxW: zod+ .number()+ .min(1)+ .max(canvasesDraftCreateBodyProjectOneComponentOneSizeOneMaxWMax)+ .optional()+ .describe("Widest allowed width; omit for no cap below the grid's width."),+ maxH: zod+ .number()+ .min(1)+ .max(canvasesDraftCreateBodyProjectOneComponentOneSizeOneMaxHMax)+ .optional()+ .describe('Tallest allowed height; omit for no cap.'),+ })+ .describe("A component's grid-size contract, in grid units.")+ .describe('Grid-size contract for placements of this component.'),+ configSchema: zod+ .record(zod.string(), zod.unknown())+ .optional()+ .describe(+ 'JSON Schema (\"type\": \"object\") for a placement\'s config. The host validates each placement\'s config against it and passes the validated object to the widget at mount.'+ ),+ })+ .describe("A component's placement contract: how grid canvases may place and configure it.")+ .optional()+ .describe(+ 'Placement contract, required for (and only allowed on) component-kind canvases: the grid size the component takes and the JSON Schema of its per-placement config.'+ ),capabilities: zod.object({posthog: zod.object({@@ -358,6 +444,18 @@ export const canvasesPublishCreateBodyProjectOneAssetsContentMax = 2796204export const canvasesPublishCreateBodyProjectOneAssetsContentRegExp = new RegExp('^(?:[A-Za-z0-9+\/]{4})\*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$')+export const canvasesPublishCreateBodyProjectOneComponentOneSizeOneDefaultWMax = 12++export const canvasesPublishCreateBodyProjectOneComponentOneSizeOneDefaultHMax = 40++export const canvasesPublishCreateBodyProjectOneComponentOneSizeOneMinWMax = 12++export const canvasesPublishCreateBodyProjectOneComponentOneSizeOneMinHMax = 40++export const canvasesPublishCreateBodyProjectOneComponentOneSizeOneMaxWMax = 12++export const canvasesPublishCreateBodyProjectOneComponentOneSizeOneMaxHMax = 40+export const canvasesPublishCreateBodyProjectOneCapabilitiesOnePosthogInsightsItemMax = 128export const canvasesPublishCreateBodyProjectOneCapabilitiesOnePosthogInsightsMax = 100@@ -426,6 +524,57 @@ export const CanvasesPublishCreateBody = /* @__PURE__ */ zod.string().optional().describe('Version of the host-injected `ph` canvas SDK the project targets.'),+ component: zod+ .object({+ size: zod+ .object({+ defaultW: zod+ .number()+ .min(1)+ .max(canvasesPublishCreateBodyProjectOneComponentOneSizeOneDefaultWMax)+ .describe('Width a new placement starts at, in grid columns.'),+ defaultH: zod+ .number()+ .min(1)+ .max(canvasesPublishCreateBodyProjectOneComponentOneSizeOneDefaultHMax)+ .describe('Height a new placement starts at, in grid rows.'),+ minW: zod+ .number()+ .min(1)+ .max(canvasesPublishCreateBodyProjectOneComponentOneSizeOneMinWMax)+ .describe('Narrowest width the component renders usefully at.'),+ minH: zod+ .number()+ .min(1)+ .max(canvasesPublishCreateBodyProjectOneComponentOneSizeOneMinHMax)+ .describe('Shortest height the component renders usefully at.'),+ maxW: zod+ .number()+ .min(1)+ .max(canvasesPublishCreateBodyProjectOneComponentOneSizeOneMaxWMax)+ .optional()+ .describe("Widest allowed width; omit for no cap below the grid's width."),+ maxH: zod+ .number()+ .min(1)+ .max(canvasesPublishCreateBodyProjectOneComponentOneSizeOneMaxHMax)+ .optional()+ .describe('Tallest allowed height; omit for no cap.'),+ })+ .describe("A component's grid-size contract, in grid units.")+ .describe('Grid-size contract for placements of this component.'),+ configSchema: zod+ .record(zod.string(), zod.unknown())+ .optional()+ .describe(+ 'JSON Schema (\"type\": \"object\") for a placement\'s config. The host validates each placement\'s config against it and passes the validated object to the widget at mount.'+ ),+ })+ .describe("A component's placement contract: how grid canvases may place and configure it.")+ .optional()+ .describe(+ 'Placement contract, required for (and only allowed on) component-kind canvases: the grid size the component takes and the JSON Schema of its per-placement config.'+ ),capabilities: zod.object({posthog: zod.object({@@ -562,6 +711,18 @@ export const canvasesValidateCreateBodyProjectOneAssetsContentMax = 2796204export const canvasesValidateCreateBodyProjectOneAssetsContentRegExp = new RegExp('^(?:[A-Za-z0-9+\/]{4})\*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$')+export const canvasesValidateCreateBodyProjectOneComponentOneSizeOneDefaultWMax = 12++export const canvasesValidateCreateBodyProjectOneComponentOneSizeOneDefaultHMax = 40++export const canvasesValidateCreateBodyProjectOneComponentOneSizeOneMinWMax = 12++export const canvasesValidateCreateBodyProjectOneComponentOneSizeOneMinHMax = 40++export const canvasesValidateCreateBodyProjectOneComponentOneSizeOneMaxWMax = 12++export const canvasesValidateCreateBodyProjectOneComponentOneSizeOneMaxHMax = 40+export const canvasesValidateCreateBodyProjectOneCapabilitiesOnePosthogInsightsItemMax = 128export const canvasesValidateCreateBodyProjectOneCapabilitiesOnePosthogInsightsMax = 100@@ -628,6 +789,57 @@ export const CanvasesValidateCreateBody = /* @__PURE__ */ zod.string().optional().describe('Version of the host-injected `ph` canvas SDK the project targets.'),+ component: zod+ .object({+ size: zod+ .object({+ defaultW: zod+ .number()+ .min(1)+ .max(canvasesValidateCreateBodyProjectOneComponentOneSizeOneDefaultWMax)+ .describe('Width a new placement starts at, in grid columns.'),+ defaultH: zod+ .number()+ .min(1)+ .max(canvasesValidateCreateBodyProjectOneComponentOneSizeOneDefaultHMax)+ .describe('Height a new placement starts at, in grid rows.'),+ minW: zod+ .number()+ .min(1)+ .max(canvasesValidateCreateBodyProjectOneComponentOneSizeOneMinWMax)+ .describe('Narrowest width the component renders usefully at.'),+ minH: zod+ .number()+ .min(1)+ .max(canvasesValidateCreateBodyProjectOneComponentOneSizeOneMinHMax)+ .describe('Shortest height the component renders usefully at.'),+ maxW: zod+ .number()+ .min(1)+ .max(canvasesValidateCreateBodyProjectOneComponentOneSizeOneMaxWMax)+ .optional()+ .describe("Widest allowed width; omit for no cap below the grid's width."),+ maxH: zod+ .number()+ .min(1)+ .max(canvasesValidateCreateBodyProjectOneComponentOneSizeOneMaxHMax)+ .optional()+ .describe('Tallest allowed height; omit for no cap.'),+ })+ .describe("A component's grid-size contract, in grid units.")+ .describe('Grid-size contract for placements of this component.'),+ configSchema: zod+ .record(zod.string(), zod.unknown())+ .optional()+ .describe(+ 'JSON Schema (\"type\": \"object\") for a placement\'s config. The host validates each placement\'s config against it and passes the validated object to the widget at mount.'+ ),+ })+ .describe("A component's placement contract: how grid canvases may place and configure it.")+ .optional()+ .describe(+ 'Placement contract, required for (and only allowed on) component-kind canvases: the grid size the component takes and the JSON Schema of its per-placement config.'+ ),capabilities: zod.object({posthog: zod.object({diff --git a/services/mcp/src/tools/generated/canvas.ts b/services/mcp/src/tools/generated/canvas.tsindex 75f9ed59c590..84a044d2215e 100644--- a/services/mcp/src/tools/generated/canvas.ts+++ b/services/mcp/src/tools/generated/canvas.ts@@ -64,6 +64,12 @@ const canvasCreate = (): ToolBase<typeof CanvasCreateSchema, Schemas.Canvas> =>if (params.channel_id !== undefined) {body['channel_id'] = params.channel_id}+ if (params.kind !== undefined) {+ body['kind'] = params.kind+ }+ if (params.description !== undefined) {+ body['description'] = params.description+ }if (params.template_id !== undefined) {body['template_id'] = params.template_id}@@ -167,8 +173,10 @@ const canvasList = (): ToolBase<typeof CanvasListSchema, Schemas.PaginatedCanvaspath: `/api/projects/${encodeURIComponent(String(projectId))}/canvases/`,query: {channel: params.channel,+ kind: params.kind,limit: params.limit,offset: params.offset,+ search: params.search,},})return resultdiff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-create.jsonindex f94c23b6298d..1344bca5a16f 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-create.json@@ -5,6 +5,17 @@"description": "Id of the channel to create the canvas in — the channel the task was created in, from the task's context. Use channel-list only to resolve a channel the user named; never pick a channel from the listing yourself (the personal #me channel is not a default).","type": "string"},+ "description": {+ "default": "",+ "description": "Short prose describing the canvas. For components this is the store-search text agents match against — say what the widget shows and what its config controls.",+ "type": "string"+ },+ "kind": {+ "default": "freeform",+ "description": "What to create: 'freeform' (a standalone app), 'component' (a reusable widget for grids — its published project must declare a `component` placement contract), or 'grid' (a composition of components, edited through the layout endpoints).\n\n* `freeform` - freeform\n* `grid` - grid\n* `component` - component",+ "enum": ["freeform", "grid", "component"],+ "type": "string"+ },"name": {"description": "Display name for the canvas.","maxLength": 400,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-draft-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-draft-create.jsonindex eff1b31efe6e..9bd7463c0bf1 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-draft-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-draft-create.json@@ -120,6 +120,64 @@"required": ["posthog", "network"],"type": "object"},+ "component": {+ "description": "Placement contract, required for (and only allowed on) component-kind canvases: the grid size the component takes and the JSON Schema of its per-placement config.",+ "properties": {+ "configSchema": {+ "additionalProperties": {},+ "description": "JSON Schema (\"type\": \"object\") for a placement's config. The host validates each placement's config against it and passes the validated object to the widget at mount.",+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ "size": {+ "description": "Grid-size contract for placements of this component.",+ "properties": {+ "defaultH": {+ "description": "Height a new placement starts at, in grid rows.",+ "maximum": 40,+ "minimum": 1,+ "type": "number"+ },+ "defaultW": {+ "description": "Width a new placement starts at, in grid columns.",+ "maximum": 12,+ "minimum": 1,+ "type": "number"+ },+ "maxH": {+ "description": "Tallest allowed height; omit for no cap.",+ "maximum": 40,+ "minimum": 1,+ "type": "number"+ },+ "maxW": {+ "description": "Widest allowed width; omit for no cap below the grid's width.",+ "maximum": 12,+ "minimum": 1,+ "type": "number"+ },+ "minH": {+ "description": "Shortest height the component renders usefully at.",+ "maximum": 40,+ "minimum": 1,+ "type": "number"+ },+ "minW": {+ "description": "Narrowest width the component renders usefully at.",+ "maximum": 12,+ "minimum": 1,+ "type": "number"+ }+ },+ "required": ["defaultW", "defaultH", "minW", "minH"],+ "type": "object"+ }+ },+ "required": ["size"],+ "type": "object"+ },"dependencies": {"additionalProperties": {"type": "string"diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-list.jsonindex 6789377efd3a..1cafad562613 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-list.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-list.json@@ -5,6 +5,11 @@"description": "Only return canvases in this channel (channel id).","type": "string"},+ "kind": {+ "description": "Only return canvases of this kind. kind=component lists the component store.",+ "enum": ["component", "freeform", "grid"],+ "type": "string"+ },"limit": {"description": "Number of results to return per page.","type": "number"@@ -12,6 +17,10 @@"offset": {"description": "The initial index from which to return the results.","type": "number"+ },+ "search": {+ "description": "Only return canvases whose name or description contains this text (case-insensitive).",+ "type": "string"}},"type": "object"diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-publish-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-publish-create.jsonindex bbfdcfba67fa..fd3433715134 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-publish-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-publish-create.json@@ -136,6 +136,64 @@"required": ["posthog", "network"],"type": "object"},+ "component": {+ "description": "Placement contract, required for (and only allowed on) component-kind canvases: the grid size the component takes and the JSON Schema of its per-placement config.",+ "properties": {+ "configSchema": {+ "additionalProperties": {},+ "description": "JSON Schema (\"type\": \"object\") for a placement's config. The host validates each placement's config against it and passes the validated object to the widget at mount.",+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ "size": {+ "description": "Grid-size contract for placements of this component.",+ "properties": {+ "defaultH": {+ "description": "Height a new placement starts at, in grid rows.",+ "maximum": 40,+ "minimum": 1,+ "type": "number"+ },+ "defaultW": {+ "description": "Width a new placement starts at, in grid columns.",+ "maximum": 12,+ "minimum": 1,+ "type": "number"+ },+ "maxH": {+ "description": "Tallest allowed height; omit for no cap.",+ "maximum": 40,+ "minimum": 1,+ "type": "number"+ },+ "maxW": {+ "description": "Widest allowed width; omit for no cap below the grid's width.",+ "maximum": 12,+ "minimum": 1,+ "type": "number"+ },+ "minH": {+ "description": "Shortest height the component renders usefully at.",+ "maximum": 40,+ "minimum": 1,+ "type": "number"+ },+ "minW": {+ "description": "Narrowest width the component renders usefully at.",+ "maximum": 12,+ "minimum": 1,+ "type": "number"+ }+ },+ "required": ["defaultW", "defaultH", "minW", "minH"],+ "type": "object"+ }+ },+ "required": ["size"],+ "type": "object"+ },"dependencies": {"additionalProperties": {"type": "string"diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-validate-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-validate-create.jsonindex 526d734b955f..2d43fec6a3b1 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-validate-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-validate-create.json@@ -120,6 +120,64 @@"required": ["posthog", "network"],"type": "object"},+ "component": {+ "description": "Placement contract, required for (and only allowed on) component-kind canvases: the grid size the component takes and the JSON Schema of its per-placement config.",+ "properties": {+ "configSchema": {+ "additionalProperties": {},+ "description": "JSON Schema (\"type\": \"object\") for a placement's config. The host validates each placement's config against it and passes the validated object to the widget at mount.",+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ "size": {+ "description": "Grid-size contract for placements of this component.",+ "properties": {+ "defaultH": {+ "description": "Height a new placement starts at, in grid rows.",+ "maximum": 40,+ "minimum": 1,+ "type": "number"+ },+ "defaultW": {+ "description": "Width a new placement starts at, in grid columns.",+ "maximum": 12,+ "minimum": 1,+ "type": "number"+ },+ "maxH": {+ "description": "Tallest allowed height; omit for no cap.",+ "maximum": 40,+ "minimum": 1,+ "type": "number"+ },+ "maxW": {+ "description": "Widest allowed width; omit for no cap below the grid's width.",+ "maximum": 12,+ "minimum": 1,+ "type": "number"+ },+ "minH": {+ "description": "Shortest height the component renders usefully at.",+ "maximum": 40,+ "minimum": 1,+ "type": "number"+ },+ "minW": {+ "description": "Narrowest width the component renders usefully at.",+ "maximum": 12,+ "minimum": 1,+ "type": "number"+ }+ },+ "required": ["defaultW", "defaultH", "minW", "minH"],+ "type": "object"+ }+ },+ "required": ["size"],+ "type": "object"+ },"dependencies": {"additionalProperties": {"type": "string"