Skip to content

: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.

feat(canvas): load canvases in one request with artifact caching (#90077)

Peter Kirkham16303a505e08
diff --git a/docs/internal/canvas-delivery.md b/docs/internal/canvas-delivery.md
new file mode 100644
index 000000000000..b294aa86647f
--- /dev/null
+++ b/docs/internal/canvas-delivery.md
@@ -0,0 +1,86 @@
+# Canvas delivery and CDN setup
+
+## API responses
+
+`GET /api/projects/{project_id}/canvases/{canvas_id}/view/` returns the canvas record, its published build and signed artifact URL, and its active-build state.
+Before a renderable build exists, it also returns the head source.
+For grids, it returns the layout and the visible components' renderable builds.
+Component expansion uses the same access rules as direct canvas reads, including task-sandbox restrictions.
+
+`GET .../layout/?include_components=true` adds component build details to the layout response.
+`GET .../builds/?scope=slim` limits the build list to the published build, head-version builds, and active builds within the existing response window.
+A requested historical version can still add its retained build.
+
+These endpoints return `Cache-Control: private, no-cache` and a content-based ETag.
+Send the ETag in `If-None-Match` to receive a bodyless `304` when the response has not changed.
+Permission checks and response construction still run before revalidation.
+Component publication, visibility changes, and renewed signed URLs change the validator.
+A view response that lacks source or layout because storage failed uses `private, no-store` and has no ETag.
+
+Keep all `/api/` responses outside the CDN cache.
+The combined endpoint reduces request count only when the client uses it.
+
+## Artifact origin
+
+Built HTML and JavaScript are untrusted user content.
+Serve them from a dedicated HTTPS origin, never the PostHog application origin or a host that receives its session cookies.
+Use a separate registrable domain if application cookies cover subdomains.
+
+`CANVAS_ARTIFACT_ORIGIN` must be a bare HTTPS origin, without a path, query, or credentials.
+Every process that creates artifact URLs must use the same origin and compatible signing keys as the artifact-serving process.
+Keep the existing `CANVAS_ARTIFACT_SIGNING_KEYS` configuration, or the existing `SECRET_KEY` fallback.
+Do not rotate keys as part of CDN setup.
+
+The CDN must forward requests to the existing Django artifact handler.
+Do not point it directly at the object-storage bucket: that bypasses token, build, deletion, and manifest checks.
+The handler accepts only the Host configured in `CANVAS_ARTIFACT_ORIGIN`.
+Forward that Host through the CDN and ingress, with matching TLS and host allowlists.
+The backend connection can use a separate origin hostname, but the HTTP Host must still match the artifact origin.
+
+## Cache policy
+
+Shared caching is off by default:
+
+```text
+CANVAS_ARTIFACT_SHARED_CACHE_SECONDS=0
+```
+
+With a positive value, successful artifact responses include `public` and a bounded `s-maxage`.
+The shared-cache lifetime cannot exceed the signed token's remaining lifetime.
+`must-revalidate` prevents a compliant cache from serving stale content after that lifetime.
+The existing browser policy remains `max-age=31536000, immutable`.
+
+Configure the CDN as follows:
+
+1. Cache only successful `GET` and `HEAD` responses under `/canvas-artifacts/`.
+2. Keep the complete host and path in the cache key, including the signed token and asset path. Do not remove or normalize the token. Preserve query strings unless an explicit rule rejects them.
+3. Honor the origin's `Cache-Control`, including `private`, `s-maxage`, and `must-revalidate`. Set the minimum cache TTL to zero. Do not impose a fixed edge TTL that overrides the response.
+4. Disable stale-on-error, stale-while-revalidate, offline copies, and negative caching for this route. Do not cache `403`, `404`, or `5xx` responses.
+5. Do not forward application cookies or session authorization. The signed token in the path is the credential. Do not add `Set-Cookie` to artifact responses.
+6. Preserve `Content-Type`, `Content-Encoding`, `Content-Disposition`, `ETag`, `Cache-Control`, `Content-Security-Policy`, `Access-Control-Allow-Origin`, `Cross-Origin-Resource-Policy`, `Referrer-Policy`, `X-Content-Type-Options`, and `Permissions-Policy`, including on `304` responses. Do not add `X-Frame-Options: DENY` or `SAMEORIGIN`.
+7. Disable HTML and JavaScript rewriting. Redact signed-token paths from access logs, analytics, and support attachments.
+
+For CloudFront, use a custom cache policy with minimum TTL zero, forward the artifact Host, and set error-cache TTLs to zero.
+For Cloudflare, enable caching only for the artifact route, enable Origin Cache Control, and do not override the edge TTL or enable Always Online for that route.
+Check the provider's behavior with an expired token before enabling shared caching.
+
+## Rollout and verification
+
+1. Deploy the backend with shared caching set to zero. Confirm that direct artifact delivery still works.
+2. Configure the CDN, certificate, origin route, and DNS with caching disabled. Prefer retaining the existing public artifact hostname to avoid changing issued URLs and host allowlists.
+3. Add the cache setting to the deployment configuration of artifact-serving web processes. It is a non-secret integer. If deployment uses a secret reference, create the referenced value before deploying that reference.
+4. Enable a short shared TTL, such as `300`, in one environment or region first. Processes that only sign URLs do not need a positive shared TTL.
+5. Request the same signed URL twice and confirm a cache miss followed by a hit. Check the provider cache-status header and `Age`, without publishing the token.
+6. Confirm that a token changed by one character, an expired token, an unknown asset, and the wrong Host do not return cached content. Test expiry both on a warm cache and after a cache miss.
+7. Open a freeform canvas and a grid. Confirm that module scripts load and that `ph.query`, `ph.state`, and declared connectors still work through the existing host bridge. Check the console for CORS and CSP failures.
+8. Publish a component, then remove access to it. Confirm that a conditional grid-view request returns a new `200` response and omits inaccessible components.
+9. Check artifact latency, cache hit ratio, origin errors, and canvas-open failures. Roll out further only after these checks pass.
+
+A cache hit does not recheck database state.
+Deleting a canvas, revoking a signing key, or removing a build can take up to the configured shared TTL to stop new edge responses.
+Previously downloaded content cannot be revoked, and the existing browser cache may still hold it.
+Keep shared caching disabled if this delay is not acceptable.
+Live query, state, action, and connector calls remain authenticated API requests; the CDN must not cache them.
+
+To roll back, set the shared TTL to zero, disable the CDN cache rule, and purge existing artifact cache entries.
+Changing the environment variable alone does not remove objects that the edge already cached.
diff --git a/posthog/settings/canvas.py b/posthog/settings/canvas.py
index 6a23e3e6df89..ff8ba7158c5b 100644
--- a/posthog/settings/canvas.py
+++ b/posthog/settings/canvas.py
@@ -1,7 +1,7 @@
import os
from posthog.settings.base_variables import BASE_DIR, TEST
-from posthog.settings.utils import get_list
+from posthog.settings.utils import get_from_env, get_list
CANVAS_ARTIFACT_ORIGIN = os.getenv("CANVAS_ARTIFACT_ORIGIN", "").rstrip("/")
# Optional dedicated keys. Artifact signing otherwise uses SECRET_KEY and its
@@ -10,6 +10,9 @@ CANVAS_ARTIFACT_SIGNING_KEYS = get_list(os.getenv("CANVAS_ARTIFACT_SIGNING_KEYS"
if TEST and not CANVAS_ARTIFACT_SIGNING_KEYS:
CANVAS_ARTIFACT_SIGNING_KEYS = ["canvas-artifact-development-key-32-bytes"]
+# Shared caching is opt-in. Each response also caps this TTL at token expiry.
+CANVAS_ARTIFACT_SHARED_CACHE_SECONDS = get_from_env("CANVAS_ARTIFACT_SHARED_CACHE_SECONDS", 0, type_cast=int)
+
# The canvas builder package (build.mjs + manifest.json + npm lockfile). A
# settings constant rather than an import so the tasks product can bake it
# into the CANVAS_BUILD sandbox image without a tasks → canvas dependency.
diff --git a/products/canvas/backend/artifacts.py b/products/canvas/backend/artifacts.py
index 2d8cf77a2dc1..2c2c45cb5c2e 100644
--- a/products/canvas/backend/artifacts.py
+++ b/products/canvas/backend/artifacts.py
@@ -11,6 +11,7 @@ Integrity is verified when artifacts are written and again when they are read
from object storage. The manifest hash is also used as the response ETag.
"""
+import math
import time
import hashlib
from typing import Any
@@ -107,6 +108,7 @@ def canvas_artifact(request: HttpRequest, token: str, artifact_path: str) -> Htt
if settings.CANVAS_ARTIFACT_ORIGIN and (configured_host is None or request.get_host().lower() != configured_host):
raise Http404
claims = _read_token(token)
+ token_expires_at = (claims["bucket"] + 2) * ARTIFACT_TOKEN_BUCKET_SECONDS
team_id = claims.get("team_id")
if not isinstance(team_id, int) or isinstance(team_id, bool):
raise Http404
@@ -140,7 +142,7 @@ def canvas_artifact(request: HttpRequest, token: str, artifact_path: str) -> Htt
if request.headers.get("If-None-Match") == etag:
response: HttpResponse = HttpResponseNotModified()
response["Content-Type"] = content_type
- return _with_artifact_headers(response, etag, build.manifest)
+ return _with_artifact_headers(response, etag, build.manifest, token_expires_at)
try:
content = object_storage.read_bytes(f"{build.artifact_object_prefix}/{artifact_path}")
@@ -154,12 +156,23 @@ def canvas_artifact(request: HttpRequest, token: str, artifact_path: str) -> Htt
raise Http404
response = HttpResponse(content, content_type=content_type)
response["Content-Disposition"] = "inline"
- return _with_artifact_headers(response, etag, build.manifest)
+ return _with_artifact_headers(response, etag, build.manifest, token_expires_at)
-def _with_artifact_headers(response: HttpResponse, etag: str, manifest: dict) -> HttpResponse:
+def _with_artifact_headers(response: HttpResponse, etag: str, manifest: dict, token_expires_at: int) -> HttpResponse:
response["ETag"] = etag
- response["Cache-Control"] = "private, max-age=31536000, immutable"
+ shared_cache_seconds = settings.CANVAS_ARTIFACT_SHARED_CACHE_SECONDS
+ if shared_cache_seconds > 0:
+ shared_cache_seconds = max(0, min(shared_cache_seconds, token_expires_at - math.ceil(time.time())))
+ # CDN mode. Every header below still applies, and in particular the
+ # CORS and CSP headers must survive the CDN unchanged, or the sandboxed
+ # iframe's module fetches (and with them ph.query/ph.state canvases)
+ # break. Configure the CDN to forward these headers as-is.
+ response["Cache-Control"] = (
+ f"public, max-age=31536000, s-maxage={shared_cache_seconds}, must-revalidate, immutable"
+ )
+ else:
+ response["Cache-Control"] = "private, max-age=31536000, immutable"
response["Cross-Origin-Resource-Policy"] = "cross-origin"
# The canvas iframe is sandboxed without allow-same-origin, so its document
# has an opaque origin and the entry's module scripts are fetched in CORS
diff --git a/products/canvas/backend/presentation/serializers.py b/products/canvas/backend/presentation/serializers.py
index 303848ab6065..1fc7a8756a35 100644
--- a/products/canvas/backend/presentation/serializers.py
+++ b/products/canvas/backend/presentation/serializers.py
@@ -897,6 +897,87 @@ class CanvasBuildsResponseSerializer(serializers.Serializer):
)
+class CanvasComponentLifecycleSerializer(serializers.Serializer):
+ """The renderable build of one component referenced by a grid layout, shaped
+ like the builds endpoint's response so clients reuse one lifecycle reader."""
+
+ canvas_id = serializers.CharField(help_text="Id of the component canvas.")
+ requested_version_id = serializers.CharField(
+ allow_null=True,
+ help_text="The source version the placement pins, or null when it follows the latest.",
+ )
+ published_build_id = serializers.CharField(
+ allow_null=True,
+ help_text="Id of the component's live build. Null until a build completes.",
+ )
+ current_version_id = serializers.CharField(
+ allow_null=True,
+ help_text="Id of the source version the component's head points at.",
+ )
+ builds = CanvasBuildSerializer(
+ many=True,
+ help_text="The build the placement renders (live, or the pinned version's retained build). Empty when none is renderable.",
+ )
+
+
+class CanvasViewResponseSerializer(serializers.Serializer):
+ """Everything a client needs to open a canvas, in one round trip.
+
+ Replaces the record → builds → source waterfall: the record, the live
+ build (with its signed artifact URL), and — only when there is nothing
+ built to render — the head source project (freeform/component) or the
+ layout document (grid)."""
+
+ canvas = CanvasSerializer(help_text="The canvas record.")
+ published_build = CanvasBuildSerializer(
+ allow_null=True,
+ help_text="The live build with its signed artifact URL. Null until a build completes.",
+ )
+ current_version_id = serializers.CharField(
+ allow_null=True,
+ help_text="Id of the source version the canvas's head points at. Null before the first publish.",
+ )
+ has_active_build = serializers.BooleanField(
+ help_text="True while a build is queued or running — poll the builds endpoint until it settles.",
+ )
+ source = CanvasSourceProjectSerializer( # type: ignore[assignment] # field named `source` shadows DRF Field.source
+ allow_null=True,
+ required=False,
+ help_text=(
+ "The head source project, present only when the canvas has no live build to render "
+ "(the client-side fallback tier). Null otherwise, and always null for grid canvases."
+ ),
+ )
+ layout = CanvasLayoutSerializer(
+ allow_null=True,
+ required=False,
+ help_text="For grid canvases: the head layout document. Null for other kinds.",
+ )
+ component_lifecycles = CanvasComponentLifecycleSerializer(
+ many=True,
+ required=False,
+ help_text=(
+ "For grid canvases: the renderable build of every component the layout's live placements "
+ "reference, so the grid renders from this one call. Absent for other kinds."
+ ),
+ )
+
+
+class CanvasLayoutWithComponentsResponseSerializer(CanvasLayoutResponseSerializer):
+ """The layout response, plus (when requested) the renderable build of every
+ component the layout places — so a grid opens on one round trip instead of
+ one builds fetch per placement."""
+
+ component_lifecycles = CanvasComponentLifecycleSerializer(
+ many=True,
+ required=False,
+ help_text=(
+ "One entry per distinct (component, pinned version) the layout's live placements reference, "
+ "present only when the request passes include_components. Components the caller may not see are omitted."
+ ),
+ )
+
+
class CanvasBuildActionSerializer(serializers.Serializer):
action = serializers.ChoiceField(choices=["retry", "pin", "unpin", "cancel"])
build_id = serializers.UUIDField()
diff --git a/products/canvas/backend/presentation/views.py b/products/canvas/backend/presentation/views.py
index b8f9f5264b12..4cb6e054e4cd 100644
--- a/products/canvas/backend/presentation/views.py
+++ b/products/canvas/backend/presentation/views.py
@@ -1,11 +1,14 @@
import json
+import hashlib
from typing import Any, cast
from uuid import UUID
from django.core.exceptions import ValidationError as DjangoValidationError
from django.db import connection, transaction
from django.db.models import Q, QuerySet
+from django.http import HttpResponseBase
from django.utils import timezone
+from django.utils.cache import get_conditional_response
import structlog
from drf_spectacular.types import OpenApiTypes
@@ -22,6 +25,7 @@ from posthog.auth import OAuthAccessTokenAuthentication
from posthog.event_usage import report_user_action
from posthog.helpers.impersonation import is_impersonated
from posthog.models.activity_logging.activity_log import Change, Detail, Trigger, log_activity
+from posthog.models.scoping import team_scope
from posthog.models.user import User
from posthog.storage.object_storage import ObjectStorageError
from posthog.temporal.oauth import SANDBOX_OAUTH_APP_CLIENT_IDS
@@ -63,7 +67,7 @@ from products.canvas.backend.presentation.serializers import (
CanvasLayoutPatchSerializer,
CanvasLayoutPublishResponseSerializer,
CanvasLayoutPublishSerializer,
- CanvasLayoutResponseSerializer,
+ CanvasLayoutWithComponentsResponseSerializer,
CanvasPromoteSerializer,
CanvasPublishConflictSerializer,
CanvasPublishCurrentVersionSerializer,
@@ -86,6 +90,7 @@ from products.canvas.backend.presentation.serializers import (
CanvasValidateRequestSerializer,
CanvasValidateResponseSerializer,
CanvasVersionSerializer,
+ CanvasViewResponseSerializer,
canvas_url,
)
from products.canvas.backend.source import apply_source_edits, has_errors, validate_source_project
@@ -168,6 +173,131 @@ def _non_grid_rejection(canvas: Canvas) -> Response | None:
)
+def _canvas_etag(*parts: Any) -> str:
+ seed = "|".join("" if part is None else str(part) for part in parts)
+ return '"' + hashlib.sha256(seed.encode()).hexdigest() + '"'
+
+
+def _with_revalidation_headers(response: HttpResponseBase, etag: str) -> HttpResponseBase:
+ # no-cache means "store, but revalidate every time": polling clients that
+ # send If-None-Match pay a hash comparison instead of a full body.
+ response["ETag"] = etag
+ response["Cache-Control"] = "private, no-cache"
+ return response
+
+
+def _conditional_response(request: Request, payload: dict[str, Any]) -> HttpResponseBase:
+ """The payload with a content ETag, or 304 when the client already has it.
+
+ get_conditional_response (not a string compare) matches weak validators
+ too, so a proxy or middleware that weakens the ETag cannot silently break
+ the 304 path."""
+ etag = _canvas_etag(json.dumps(payload, sort_keys=True, default=str))
+ not_modified = get_conditional_response(request._request, etag=etag)
+ if not_modified is not None:
+ return _with_revalidation_headers(not_modified, etag)
+ return _with_revalidation_headers(Response(payload), etag)
+
+
+def _renderable_build(build: CanvasBuild | None) -> CanvasBuild | None:
+ """The build if it can actually be served: ready, artifacts retained, and
+ manifest frozen (the serializer needs the manifest to mint the entry URL)."""
+ if (
+ build is not None
+ and build.status == CanvasBuild.STATUS_READY
+ and build.artifact_object_prefix
+ and isinstance(build.manifest, dict)
+ ):
+ return build
+ return None
+
+
+def _component_lifecycles(team_id: int, canvases: QuerySet[Canvas], layout: dict[str, Any]) -> list[dict[str, Any]]:
+ """The renderable build for each distinct (component, pinned version) the
+ layout's live placements reference.
+
+ The authorized queryset also enforces sandbox access. A component the
+ caller may not read is omitted, identically to one that is missing."""
+ placements = layout.get("placements")
+ if not isinstance(placements, list):
+ return []
+ wanted: set[tuple[str, str | None]] = set()
+ for placement in placements:
+ if not isinstance(placement, dict) or placement.get("status") != "live":
+ continue
+ component = placement.get("component")
+ if not isinstance(component, str):
+ continue
+ version = placement.get("version")
+ pinned: str | None = None
+ if isinstance(version, str) and version != "latest":
+ try:
+ pinned = str(UUID(version))
+ except ValueError:
+ continue
+ try:
+ component = str(UUID(component))
+ except ValueError:
+ continue
+ wanted.add((component, pinned))
+ if not wanted:
+ return []
+
+ component_ids = {component_id for component_id, _ in wanted}
+ pinned_version_ids = {version_id for _, version_id in wanted if version_id}
+ with team_scope(team_id):
+ components = {
+ str(canvas.id): canvas
+ for canvas in canvases.filter(id__in=component_ids, kind=Canvas.KIND_COMPONENT).select_related(
+ "published_build"
+ )
+ }
+ pinned_builds: dict[str, CanvasBuild] = {}
+ if pinned_version_ids:
+ # One row per version (its newest ready build) instead of loading a
+ # retry-loop's whole build history with manifests.
+ for build in (
+ CanvasBuild.objects.for_team(team_id)
+ .filter(
+ source_version_id__in=pinned_version_ids,
+ canvas_id__in=components.keys(),
+ status=CanvasBuild.STATUS_READY,
+ artifact_object_prefix__isnull=False,
+ )
+ .order_by("source_version_id", "-created_at")
+ .distinct("source_version_id")
+ ):
+ pinned_builds[str(build.source_version_id)] = build
+
+ entries: list[dict[str, Any]] = []
+ for component_id, pinned_version_id in sorted(wanted, key=lambda pair: (pair[0], pair[1] or "")):
+ component_canvas = components.get(component_id)
+ if component_canvas is None:
+ continue
+ if pinned_version_id:
+ pinned_build = _renderable_build(pinned_builds.get(pinned_version_id))
+ builds = [pinned_build] if pinned_build is not None and str(pinned_build.canvas_id) == component_id else []
+ else:
+ published = _renderable_build(component_canvas.published_build)
+ builds = [published] if published is not None else []
+ entries.append(
+ {
+ "canvas_id": component_id,
+ "requested_version_id": pinned_version_id,
+ "published_build_id": (
+ str(component_canvas.published_build_id) if component_canvas.published_build_id else None
+ ),
+ "current_version_id": (
+ str(component_canvas.current_source_version_id)
+ if component_canvas.current_source_version_id
+ else None
+ ),
+ "builds": builds,
+ }
+ )
+ return entries
+
+
def _wrong_kind_response(detail: str) -> Response:
return Response({"detail": detail, "code": "wrong_canvas_kind"}, status=status.HTTP_400_BAD_REQUEST)
@@ -315,6 +445,7 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.ModelViewSet):
"state",
"layout",
"connectors",
+ "view",
]
scope_object_write_actions = [
"create",
@@ -612,6 +743,63 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.ModelViewSet):
}
return Response(response)
+ @extend_schema(
+ operation_id="canvases_view_retrieve",
+ responses={
+ 200: CanvasViewResponseSerializer,
+ 304: OpenApiResponse(description="Not modified — the client's cached view payload is current."),
+ },
+ request=None,
+ )
+ @action(methods=["GET"], detail=True)
+ def view(self, request: Request, *args: Any, **kwargs: Any) -> HttpResponseBase:
+ """Everything needed to open the canvas, in one round trip.
+
+ Returns the record, the live build (with its signed artifact URL), and —
+ only when there is nothing built to render — the head source project
+ (freeform/component) or the layout document (grid). Send the response's
+ ETag back as If-None-Match to revalidate without a body.
+ """
+ canvas = self.get_object()
+ live_build = _renderable_build(canvas.published_build)
+ newest_active = (
+ canvas.builds.filter(status__in=CanvasBuild.ACTIVE_STATUSES)
+ .order_by("-created_at")
+ .values_list("id", "status")
+ .first()
+ )
+ source: dict[str, Any] | None = None
+ layout: dict[str, Any] | None = None
+ degraded = False
+ # Object storage is read only when there is no artifact to render. A
+ # storage hiccup degrades to the client's per-endpoint fallback instead
+ # of failing the whole open.
+ try:
+ if canvas.kind == Canvas.KIND_GRID:
+ layout = self._read_current_layout(canvas)
+ elif live_build is None:
+ source, _ = build_service.current_source_project(canvas)
+ except ObjectStorageError:
+ degraded = True
+ instance: dict[str, Any] = {
+ "canvas": canvas,
+ "published_build": live_build,
+ "current_version_id": (str(canvas.current_source_version_id) if canvas.current_source_version_id else None),
+ "has_active_build": newest_active is not None,
+ "source": source,
+ "layout": layout,
+ }
+ if layout is not None:
+ instance["component_lifecycles"] = _component_lifecycles(self.team_id, self.get_queryset(), layout)
+ payload = CanvasViewResponseSerializer(instance=instance).data
+ if degraded:
+ # A payload missing its source/layout must not revalidate as
+ # current after storage recovers: no validator, no caching.
+ response = Response(payload)
+ response["Cache-Control"] = "private, no-store"
+ return response
+ return _conditional_response(request, payload)
+
@extend_schema(
operation_id="canvases_versions_retrieve",
responses={200: CanvasVersionSerializer(many=True)},
@@ -1047,7 +1235,10 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.ModelViewSet):
@extend_schema(
operation_id="canvases_builds_retrieve",
- responses={200: CanvasBuildsResponseSerializer},
+ responses={
+ 200: CanvasBuildsResponseSerializer,
+ 304: OpenApiResponse(description="Not modified — the client's cached lifecycle is current."),
+ },
request=None,
parameters=[
OpenApiParameter(
@@ -1055,19 +1246,40 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.ModelViewSet):
type=OpenApiTypes.UUID,
required=False,
description="Include the retained ready build for this historical source version.",
- )
+ ),
+ OpenApiParameter(
+ name="scope",
+ type=OpenApiTypes.STR,
+ required=False,
+ description=(
+ '"slim" returns only what rendering needs — the live build, the head version\'s builds, '
+ "and anything still in flight — instead of the full recent-build history. Any other value "
+ "(or none) returns the full window."
+ ),
+ ),
],
)
@action(methods=["GET"], detail=True)
- def builds(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ def builds(self, request: Request, *args: Any, **kwargs: Any) -> HttpResponseBase:
"""Read the canvas's build lifecycle: live pointers plus recent builds.
A publish queues a build; poll this until it is ready (the live pointer
advances) or failed (fix the error diagnostics and publish again — the
- last good build stays live).
+ last good build stays live). Send the response's ETag back as
+ If-None-Match to make the poll revalidate without a body.
"""
canvas = self.get_object()
- builds = list(canvas.builds.order_by("-created_at")[:BUILDS_WINDOW])
+ if request.query_params.get("scope") == "slim":
+ # Pollers re-read this every couple of seconds; they need render
+ # state, not 20 manifests of history.
+ slim_q = Q(status__in=CanvasBuild.ACTIVE_STATUSES)
+ if canvas.published_build_id:
+ slim_q |= Q(id=canvas.published_build_id)
+ if canvas.current_source_version_id:
+ slim_q |= Q(source_version_id=canvas.current_source_version_id)
+ builds = list(canvas.builds.filter(slim_q).order_by("-created_at")[:BUILDS_WINDOW])
+ else:
+ builds = list(canvas.builds.order_by("-created_at")[:BUILDS_WINDOW])
# The live build must always be visible, even when newer (e.g. failed)
# builds have pushed it past the window.
if canvas.published_build_id and all(build.id != canvas.published_build_id for build in builds):
@@ -1089,17 +1301,18 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.ModelViewSet):
)
if historical_build is not None and all(build.id != historical_build.id for build in builds):
builds.append(historical_build)
- response = {
+ payload = {
"published_build_id": str(canvas.published_build_id) if canvas.published_build_id else None,
"current_version_id": (str(canvas.current_source_version_id) if canvas.current_source_version_id else None),
"builds": CanvasBuildSerializer(builds, many=True).data,
}
- return Response(response)
+ return _conditional_response(request, payload)
@extend_schema(
operation_id="canvases_layout_retrieve",
responses={
- 200: CanvasLayoutResponseSerializer,
+ 200: CanvasLayoutWithComponentsResponseSerializer,
+ 304: OpenApiResponse(description="Not modified — the client's cached layout is current."),
400: OpenApiResponse(description="The canvas is not a grid canvas."),
},
request=None,
@@ -1109,11 +1322,20 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.ModelViewSet):
type=str,
required=False,
description="Read this historical layout version instead of the head (for version browsing).",
- )
+ ),
+ OpenApiParameter(
+ name="include_components",
+ type=OpenApiTypes.BOOL,
+ required=False,
+ description=(
+ "Also return the renderable build (with signed artifact URL) of every component the layout's "
+ "live placements reference, so a grid renders from this one call."
+ ),
+ ),
],
)
@action(methods=["GET"], detail=True)
- def layout(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ def layout(self, request: Request, *args: Any, **kwargs: Any) -> HttpResponseBase:
"""Read a grid canvas's layout document and its `current_version_id`.
Always call this before editing: pass the returned version id as
@@ -1145,17 +1367,14 @@ class CanvasViewSet(CanvasAccessMixin, viewsets.ModelViewSet):
{"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
- )
+ instance: dict[str, Any] = {
+ "canvas": canvas,
+ "layout": layout,
+ "current_version_id": (str(canvas.current_source_version_id) if canvas.current_source_version_id else None),
+ }
+ if request.query_params.get("include_components") in ("1", "true"):
+ instance["component_lifecycles"] = _component_lifecycles(self.team_id, self.get_queryset(), layout)
+ return _conditional_response(request, CanvasLayoutWithComponentsResponseSerializer(instance=instance).data)
@extend_schema(
operation_id="canvases_layout_publish_create",
diff --git a/products/canvas/backend/tests/test_artifacts.py b/products/canvas/backend/tests/test_artifacts.py
index 08aca141fe18..e25f0aaa862e 100644
--- a/products/canvas/backend/tests/test_artifacts.py
+++ b/products/canvas/backend/tests/test_artifacts.py
@@ -93,12 +93,38 @@ class TestCanvasArtifacts(APIBaseTest):
def test_url_is_stable_within_a_bucket(self):
assert self._url() == self._url()
- def test_expired_bucket_is_rejected(self):
+ def test_shared_cache_mode_keeps_bridge_headers(self):
+ # CDN mode must change ONLY the cache policy: the CORS and CSP headers
+ # are what let the sandboxed iframe fetch its modules and keep the
+ # postMessage data/state bridge working, so losing any of them would
+ # break live-data and stateful canvases the moment a CDN fronts the
+ # artifact origin.
+ baseline = self.client.get(self._url())
+ with self.settings(CANVAS_ARTIFACT_SHARED_CACHE_SECONDS=300):
+ response = self.client.get(self._url())
+ assert response.status_code == 200
+ assert response["Cache-Control"] == "public, max-age=31536000, s-maxage=300, must-revalidate, immutable"
+ assert response["Access-Control-Allow-Origin"] == "*"
+ assert response["Cross-Origin-Resource-Policy"] == "cross-origin"
+ assert response["Content-Security-Policy"] == baseline["Content-Security-Policy"]
+
+ def test_expired_bucket_is_rejected(self) -> None:
url = self._url()
- two_buckets = artifacts.ARTIFACT_TOKEN_BUCKET_SECONDS * 2
- with patch.object(artifacts.time, "time", return_value=time.time() + two_buckets):
- response = self.client.get(url)
- assert response.status_code == 404
+ bucket = int(time.time() // artifacts.ARTIFACT_TOKEN_BUCKET_SECONDS)
+ expires_at = (bucket + 2) * artifacts.ARTIFACT_TOKEN_BUCKET_SECONDS
+ with self.settings(CANVAS_ARTIFACT_SHARED_CACHE_SECONDS=300):
+ with patch.object(artifacts.time, "time", return_value=expires_at - 10):
+ response = self.client.get(url)
+ assert response.status_code == 200
+ assert response["Cache-Control"] == (
+ "public, max-age=31536000, s-maxage=10, must-revalidate, immutable"
+ )
+ cached = self.client.get(url, HTTP_IF_NONE_MATCH=response["ETag"])
+ assert cached.status_code == 304
+ assert cached["Cache-Control"] == response["Cache-Control"]
+ with patch.object(artifacts.time, "time", return_value=expires_at):
+ response = self.client.get(url)
+ assert response.status_code == 404
def test_unknown_asset_and_unready_build_404(self):
url = self._url()
diff --git a/products/canvas/backend/tests/test_canvas_api.py b/products/canvas/backend/tests/test_canvas_api.py
index 3a30befdddbe..2c4c72063c03 100644
--- a/products/canvas/backend/tests/test_canvas_api.py
+++ b/products/canvas/backend/tests/test_canvas_api.py
@@ -20,6 +20,7 @@ from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.scoping import team_scope
from posthog.models.user import User
from posthog.models.utils import generate_random_token_personal, hash_key_value
+from posthog.storage.object_storage import ObjectStorageError
from posthog.temporal.oauth import ARRAY_APP_CLIENT_ID_DEV
from products.annotations.backend.models.annotation import Annotation
@@ -926,6 +927,79 @@ class TestCanvasSourceAndPublish(CanvasAPIBaseTest):
assert Canvas.objects.unscoped().get(id=canvas_id).legacy_code is None
+class TestCanvasViewEndpoint(CanvasAPIBaseTest):
+ def _view(self, canvas_id: str, **headers):
+ return self.client.get(f"/api/projects/{self.team.id}/canvases/{canvas_id}/view/", **headers)
+
+ def _mark_published(self, canvas_id: str) -> CanvasBuild:
+ build = CanvasBuild.objects.unscoped().filter(canvas_id=canvas_id).first()
+ assert build is not None
+ build.status = CanvasBuild.STATUS_READY
+ build.artifact_object_prefix = f"canvas_artifact/team_{self.team.id}/{canvas_id}/{build.id}"
+ build.manifest = {
+ "entryHtml": "index.html",
+ "assets": [],
+ "dependencies": {},
+ "canvasSdkVersion": "0.1.0",
+ "capabilities": {},
+ }
+ build.save()
+ Canvas.objects.unscoped().filter(pk=canvas_id).update(published_build=build)
+ return build
+
+ def test_view_before_first_build_returns_source_and_active_build(self):
+ canvas_id = self._create_canvas()
+ self._publish(canvas_id, expected_current_version_id=None)
+ body = self._view(canvas_id).json()
+ assert body["canvas"]["id"] == canvas_id
+ assert body["published_build"] is None
+ assert body["has_active_build"] is True
+ assert "src/canvas.tsx" in body["source"]["files"]
+ assert body["layout"] is None
+
+ def test_view_after_build_returns_artifact_url_and_omits_source(self):
+ canvas_id = self._create_canvas()
+ self._publish(canvas_id, expected_current_version_id=None)
+ build = self._mark_published(canvas_id)
+ body = self._view(canvas_id).json()
+ assert body["published_build"]["id"] == str(build.id)
+ assert body["published_build"]["artifact_url"].endswith("/index.html")
+ assert body["source"] is None
+
+ def test_view_revalidates_with_etag(self):
+ canvas_id = self._create_canvas()
+ first = self._publish(canvas_id, expected_current_version_id=None)
+ response = self._view(canvas_id)
+ etag = response["ETag"]
+ assert self._view(canvas_id, HTTP_IF_NONE_MATCH=etag).status_code == status.HTTP_304_NOT_MODIFIED
+ # A new publish moves the head, so the cached payload is no longer current.
+ self._publish(
+ canvas_id,
+ self._project("export default function C() { return 2 }"),
+ expected_current_version_id=first.json()["current_version_id"],
+ )
+ assert self._view(canvas_id, HTTP_IF_NONE_MATCH=etag).status_code == status.HTTP_200_OK
+
+ def test_view_of_grid_returns_layout(self):
+ canvas_id = self._create_canvas(kind="grid")
+ body = self._view(canvas_id).json()
+ assert body["layout"]["placements"] == []
+ assert body["component_lifecycles"] == []
+ assert body["source"] is None
+
+ def test_view_survives_storage_outage_without_caching_the_degraded_payload(self):
+ canvas_id = self._create_canvas()
+ self._publish(canvas_id, expected_current_version_id=None)
+ with patch.object(build_service, "current_source_project", side_effect=ObjectStorageError("down")):
+ response = self._view(canvas_id)
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["source"] is None
+ # No validator on a degraded payload: a later revalidation must not
+ # 304-pin the missing source after storage recovers.
+ assert not response.headers.get("ETag")
+ assert response["Cache-Control"] == "private, no-store"
+
+
class TestCanvasRevertAndBuilds(CanvasAPIBaseTest):
def _published_canvas(self) -> tuple[str, str, str]:
canvas_id = self._create_canvas()
@@ -1017,6 +1091,48 @@ class TestCanvasRevertAndBuilds(CanvasAPIBaseTest):
assert response.status_code == status.HTTP_200_OK
assert str(historical.id) in {build["id"] for build in response.json()["builds"]}
+ def test_builds_slim_scope_drops_stale_history_but_keeps_render_state(self):
+ canvas_id, v1, v2 = self._published_canvas()
+ published = CanvasBuild.objects.unscoped().get(canvas_id=canvas_id, source_version_id=v1)
+ published.status = CanvasBuild.STATUS_READY
+ published.save(update_fields=["status"])
+ Canvas.objects.unscoped().filter(pk=canvas_id).update(published_build=published)
+ # Stale history: failed builds of the old (non-head) version.
+ with team_scope(self.team.id):
+ stale_ids = [
+ str(
+ CanvasBuild.objects.create(
+ team_id=self.team.id,
+ canvas_id=canvas_id,
+ source_version_id=v1,
+ status=CanvasBuild.STATUS_FAILED,
+ ).id
+ )
+ for _ in range(3)
+ ]
+
+ slim = self.client.get(f"/api/projects/{self.team.id}/canvases/{canvas_id}/builds/?scope=slim").json()
+ slim_ids = {build["id"] for build in slim["builds"]}
+ assert str(published.id) in slim_ids
+ # The head version's queued build stays because its outcome is what the author watches.
+ head_build = CanvasBuild.objects.unscoped().get(canvas_id=canvas_id, source_version_id=v2)
+ assert str(head_build.id) in slim_ids
+ assert not slim_ids.intersection(stale_ids)
+
+ full = self.client.get(f"/api/projects/{self.team.id}/canvases/{canvas_id}/builds/").json()
+ assert set(stale_ids).issubset({build["id"] for build in full["builds"]})
+
+ def test_builds_etag_revalidation(self):
+ canvas_id, _, v2 = self._published_canvas()
+ url = f"/api/projects/{self.team.id}/canvases/{canvas_id}/builds/"
+ etag = self.client.get(url)["ETag"]
+ assert self.client.get(url, HTTP_IF_NONE_MATCH=etag).status_code == status.HTTP_304_NOT_MODIFIED
+ with team_scope(self.team.id):
+ CanvasBuild.objects.create(
+ team_id=self.team.id, canvas_id=canvas_id, source_version_id=v2, status=CanvasBuild.STATUS_FAILED
+ )
+ assert self.client.get(url, HTTP_IF_NONE_MATCH=etag).status_code == status.HTTP_200_OK
+
def test_build_with_pruned_artifacts_advertises_no_url(self):
canvas_id, v1, _ = self._published_canvas()
build = CanvasBuild.objects.unscoped().filter(canvas_id=canvas_id).first()
diff --git a/products/canvas/backend/tests/test_grid_layout.py b/products/canvas/backend/tests/test_grid_layout.py
index 4b1cf301ca48..34bba5763973 100644
--- a/products/canvas/backend/tests/test_grid_layout.py
+++ b/products/canvas/backend/tests/test_grid_layout.py
@@ -23,7 +23,7 @@ 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
+from products.tasks.backend.models import Channel, Task
def layout(**overrides) -> dict[str, Any]:
@@ -108,6 +108,106 @@ class TestGridLayoutApi(GridLayoutAPIBaseTest):
assert read.json()["current_version_id"] == version_id
self.enqueue.assert_not_called()
+ @parameterized.expand(["layout/?include_components=true", "view/"])
+ def test_layout_include_components_returns_renderable_builds_for_visible_components_only(
+ self, endpoint: str
+ ) -> None:
+ grid_id = self._create_grid()
+ component_id = self._create_component()
+ with team_scope(self.team.id):
+ build = CanvasBuild.objects.for_team(self.team.id).get(canvas_id=component_id)
+ build.manifest = {
+ "entryHtml": "index.html",
+ "assets": [],
+ "dependencies": {},
+ "canvasSdkVersion": "0.1.0",
+ "capabilities": {},
+ }
+ build.save(update_fields=["manifest"])
+ # A component filed in another user's personal channel: placeable
+ # only by them, so its entry must be omitted for this caller.
+ other_user = User.objects.create_and_join(self.organization, "[email protected]", None)
+ private_channel = Channel.objects.create(
+ team=self.team, name="me", channel_type=Channel.ChannelType.PERSONAL, created_by=other_user
+ )
+ private_component = Canvas.objects.create(
+ team=self.team, channel=private_channel, name="Private", kind=Canvas.KIND_COMPONENT
+ )
+ doc = layout(
+ placements=[
+ placement(id="p1", status="live", component=component_id),
+ placement(id="p2", status="live", component=str(private_component.id), x=2),
+ ]
+ )
+ with patch("products.canvas.backend.presentation.views._layout_diagnostics", return_value=[]):
+ assert self._publish_layout(grid_id, doc).status_code == status.HTTP_200_OK
+
+ url = f"/api/projects/{self.team.id}/canvases/{grid_id}/{endpoint}"
+ response = self.client.get(url)
+ assert response.status_code == status.HTTP_200_OK
+ lifecycles = response.json()["component_lifecycles"]
+ assert [entry["canvas_id"] for entry in lifecycles] == [component_id]
+ entry = lifecycles[0]
+ assert entry["published_build_id"] == str(build.id)
+ assert entry["requested_version_id"] is None
+ assert entry["builds"][0]["artifact_url"].endswith("/index.html")
+
+ etag = response["ETag"]
+ assert self.client.get(url, HTTP_IF_NONE_MATCH=f"W/{etag}").status_code == status.HTTP_304_NOT_MODIFIED
+ with team_scope(self.team.id):
+ replacement = CanvasBuild.objects.for_team(self.team.id).create(
+ team=self.team,
+ canvas_id=component_id,
+ source_version=build.source_version,
+ status=CanvasBuild.STATUS_READY,
+ artifact_object_prefix=f"canvas_artifact/team_{self.team.id}/{component_id}/replacement",
+ manifest=build.manifest,
+ )
+ Canvas.objects.for_team(self.team.id).filter(pk=component_id).update(published_build=replacement)
+ changed = self.client.get(url, HTTP_IF_NONE_MATCH=etag)
+ assert changed.status_code == status.HTTP_200_OK
+ assert changed.json()["component_lifecycles"][0]["published_build_id"] == str(replacement.id)
+
+ with team_scope(self.team.id):
+ Canvas.objects.for_team(self.team.id).filter(pk=component_id).update(channel=private_channel)
+ hidden = self.client.get(url, HTTP_IF_NONE_MATCH=changed["ETag"])
+ assert hidden.status_code == status.HTTP_200_OK
+ assert hidden.json()["component_lifecycles"] == []
+
+ self.client.force_login(other_user)
+ visible = self.client.get(url, HTTP_IF_NONE_MATCH=hidden["ETag"])
+ assert visible.status_code == status.HTTP_200_OK
+ assert {entry["canvas_id"] for entry in visible.json()["component_lifecycles"]} == {
+ component_id,
+ str(private_component.id),
+ }
+
+ without = self._get_layout(grid_id)
+ assert "component_lifecycles" not in without.json()
+
+ task = Task.objects.create(
+ team=self.team,
+ channel=self.channel,
+ created_by=other_user,
+ title="Read a grid",
+ description="Read component builds",
+ origin_product=Task.OriginProduct.USER_CREATED,
+ )
+ sandbox = self._sandbox_client(task.id, user=other_user)
+ direct = sandbox.get(
+ f"/api/projects/{self.team.id}/canvases/{component_id}/", HTTP_X_POSTHOG_TASK_ID=str(task.id)
+ )
+ assert direct.status_code == status.HTTP_404_NOT_FOUND
+ restricted = sandbox.get(url, HTTP_IF_NONE_MATCH=visible["ETag"], HTTP_X_POSTHOG_TASK_ID=str(task.id))
+ assert restricted.status_code == status.HTTP_200_OK
+ assert restricted.json()["component_lifecycles"] == []
+
+ with team_scope(self.team.id):
+ Canvas.objects.for_team(self.team.id).filter(pk=component_id).update(created_by=other_user)
+ owned = sandbox.get(url, HTTP_IF_NONE_MATCH=restricted["ETag"], HTTP_X_POSTHOG_TASK_ID=str(task.id))
+ assert owned.status_code == status.HTTP_200_OK
+ assert [entry["canvas_id"] for entry in owned.json()["component_lifecycles"]] == [component_id]
+
def test_unpublished_grid_returns_default_layout(self):
grid_id = self._create_grid()
read = self._get_layout(grid_id)
diff --git a/products/canvas/frontend/generated/api.schemas.ts b/products/canvas/frontend/generated/api.schemas.ts
index 62720f4efe3f..0df392ff72f0 100644
--- a/products/canvas/frontend/generated/api.schemas.ts
+++ b/products/canvas/frontend/generated/api.schemas.ts
@@ -1042,9 +1042,37 @@ export interface CanvasLayoutApi {
}
/**
- * A grid canvas's layout plus the version pointer edits must be based on.
+ * The renderable build of one component referenced by a grid layout, shaped
+ * like the builds endpoint's response so clients reuse one lifecycle reader.
*/
-export interface CanvasLayoutResponseApi {
+export interface CanvasComponentLifecycleApi {
+ /** Id of the component canvas. */
+ canvas_id: string
+ /**
+ * The source version the placement pins, or null when it follows the latest.
+ * @nullable
+ */
+ requested_version_id: string | null
+ /**
+ * Id of the component's live build. Null until a build completes.
+ * @nullable
+ */
+ published_build_id: string | null
+ /**
+ * Id of the source version the component's head points at.
+ * @nullable
+ */
+ current_version_id: string | null
+ /** The build the placement renders (live, or the pinned version's retained build). Empty when none is renderable. */
+ builds: CanvasBuildApi[]
+}
+
+/**
+ * The layout response, plus (when requested) the renderable build of every
+ * component the layout places — so a grid opens on one round trip instead of
+ * one builds fetch per placement.
+ */
+export interface CanvasLayoutWithComponentsResponseApi {
/** Identity and version pointers for the canvas. */
canvas: CanvasSummaryApi
/** The layout document. A grid canvas with no versions yet returns the default empty layout. */
@@ -1054,6 +1082,8 @@ export interface CanvasLayoutResponseApi {
* @nullable
*/
current_version_id: string | null
+ /** One entry per distinct (component, pinned version) the layout's live placements reference, present only when the request passes include_components. Components the caller may not see are omitted. */
+ component_lifecycles?: CanvasComponentLifecycleApi[]
}
/**
@@ -1492,6 +1522,34 @@ export interface PaginatedCanvasVersionListApi {
results: CanvasVersionApi[]
}
+/**
+ * Everything a client needs to open a canvas, in one round trip.
+ *
+ * Replaces the record → builds → source waterfall: the record, the live
+ * build (with its signed artifact URL), and — only when there is nothing
+ * built to render — the head source project (freeform/component) or the
+ * layout document (grid).
+ */
+export interface CanvasViewResponseApi {
+ /** The canvas record. */
+ canvas: CanvasApi
+ /** The live build with its signed artifact URL. Null until a build completes. */
+ published_build: CanvasBuildApi | null
+ /**
+ * Id of the source version the canvas's head points at. Null before the first publish.
+ * @nullable
+ */
+ current_version_id: string | null
+ /** True while a build is queued or running — poll the builds endpoint until it settles. */
+ has_active_build: boolean
+ /** The head source project, present only when the canvas has no live build to render (the client-side fallback tier). Null otherwise, and always null for grid canvases. */
+ source?: CanvasSourceProjectApi | null
+ /** For grid canvases: the head layout document. Null for other kinds. */
+ layout?: CanvasLayoutApi | null
+ /** For grid canvases: the renderable build of every component the layout's live placements reference, so the grid renders from this one call. Absent for other kinds. */
+ component_lifecycles?: CanvasComponentLifecycleApi[]
+}
+
/**
* One registered action verb, as the host renders it before invoking.
*/
@@ -1610,6 +1668,10 @@ export const CanvasesListKind = {
} as const
export type CanvasesBuildsRetrieveParams = {
+ /**
+ * "slim" returns only what rendering needs — the live build, the head version's builds, and anything still in flight — instead of the full recent-build history. Any other value (or none) returns the full window.
+ */
+ scope?: string
/**
* Include the retained ready build for this historical source version.
*/
@@ -1628,6 +1690,10 @@ export type CanvasesDraftsRetrieveParams = {
}
export type CanvasesLayoutRetrieveParams = {
+ /**
+ * Also return the renderable build (with signed artifact URL) of every component the layout's live placements reference, so a grid renders from this one call.
+ */
+ include_components?: boolean
/**
* Read this historical layout version instead of the head (for version browsing).
*/
diff --git a/products/canvas/frontend/generated/api.ts b/products/canvas/frontend/generated/api.ts
index 5090a76dbad7..ad820f0da477 100644
--- a/products/canvas/frontend/generated/api.ts
+++ b/products/canvas/frontend/generated/api.ts
@@ -27,7 +27,7 @@ import type {
CanvasLayoutPatchApi,
CanvasLayoutPublishApi,
CanvasLayoutPublishResponseApi,
- CanvasLayoutResponseApi,
+ CanvasLayoutWithComponentsResponseApi,
CanvasPromoteApi,
CanvasPublishCurrentVersionApi,
CanvasReportErrorApi,
@@ -44,6 +44,7 @@ import type {
CanvasStateSetApi,
CanvasValidateRequestApi,
CanvasValidateResponseApi,
+ CanvasViewResponseApi,
CanvasesBuildsRetrieveParams,
CanvasesConnectorsRetrieveParams,
CanvasesDraftsRetrieveParams,
@@ -212,7 +213,8 @@ export const getCanvasesBuildsRetrieveUrl = (projectId: string, id: string, para
*
* A publish queues a build; poll this until it is ready (the live pointer
* advances) or failed (fix the error diagnostics and publish again — the
- * last good build stays live).
+ * last good build stays live). Send the response's ETag back as
+ * If-None-Match to make the poll revalidate without a body.
*/
export const canvasesBuildsRetrieve = async (
projectId: string,
@@ -390,8 +392,8 @@ export const canvasesLayoutRetrieve = async (
id: string,
params?: CanvasesLayoutRetrieveParams,
options?: RequestInit
-): Promise<CanvasLayoutResponseApi> => {
- return apiMutator<CanvasLayoutResponseApi>(getCanvasesLayoutRetrieveUrl(projectId, id, params), {
+): Promise<CanvasLayoutWithComponentsResponseApi> => {
+ return apiMutator<CanvasLayoutWithComponentsResponseApi>(getCanvasesLayoutRetrieveUrl(projectId, id, params), {
...options,
method: 'GET',
})
@@ -765,6 +767,29 @@ export const canvasesVersionsRetrieve = async (
})
}
+export const getCanvasesViewRetrieveUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/canvases/${id}/view/`
+}
+
+/**
+ * Everything needed to open the canvas, in one round trip.
+ *
+ * Returns the record, the live build (with its signed artifact URL), and —
+ * only when there is nothing built to render — the head source project
+ * (freeform/component) or the layout document (grid). Send the response's
+ * ETag back as If-None-Match to revalidate without a body.
+ */
+export const canvasesViewRetrieve = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<CanvasViewResponseApi> => {
+ return apiMutator<CanvasViewResponseApi>(getCanvasesViewRetrieveUrl(projectId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getCanvasesActionsRetrieveUrl = (projectId: string) => {
return `/api/projects/${projectId}/canvases/actions/`
}
diff --git a/products/canvas/mcp/tools.yaml b/products/canvas/mcp/tools.yaml
index 8fa1e30da346..4438bcd4882f 100644
--- a/products/canvas/mcp/tools.yaml
+++ b/products/canvas/mcp/tools.yaml
@@ -423,3 +423,6 @@ tools:
canvases-versions-retrieve:
operation: canvases_versions_retrieve
enabled: false
+ canvases-view-retrieve:
+ operation: canvases_view_retrieve
+ enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 3b17276ba4b9..480201a1928e 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -16238,6 +16238,32 @@ export namespace Schemas {
connectors_added: CanvasConnectorDeclaration[];
}
+ /**
+ * The renderable build of one component referenced by a grid layout, shaped
+ * like the builds endpoint's response so clients reuse one lifecycle reader.
+ */
+ export interface CanvasComponentLifecycle {
+ /** Id of the component canvas. */
+ canvas_id: string;
+ /**
+ * The source version the placement pins, or null when it follows the latest.
+ * @nullable
+ */
+ requested_version_id: string | null;
+ /**
+ * Id of the component's live build. Null until a build completes.
+ * @nullable
+ */
+ published_build_id: string | null;
+ /**
+ * Id of the source version the component's head points at.
+ * @nullable
+ */
+ current_version_id: string | null;
+ /** The build the placement renders (live, or the pinned version's retained build). Empty when none is renderable. */
+ builds: CanvasBuild[];
+ }
+
/**
* * `native` - Native
* * `mcp` - Mcp
@@ -16845,9 +16871,11 @@ export namespace Schemas {
}
/**
- * A grid canvas's layout plus the version pointer edits must be based on.
+ * The layout response, plus (when requested) the renderable build of every
+ * component the layout places — so a grid opens on one round trip instead of
+ * one builds fetch per placement.
*/
- export interface CanvasLayoutResponse {
+ export interface CanvasLayoutWithComponentsResponse {
/** Identity and version pointers for the canvas. */
canvas: CanvasSummary;
/** The layout document. A grid canvas with no versions yet returns the default empty layout. */
@@ -16857,6 +16885,8 @@ export namespace Schemas {
* @nullable
*/
current_version_id: string | null;
+ /** One entry per distinct (component, pinned version) the layout's live placements reference, present only when the request passes include_components. Components the caller may not see are omitted. */
+ component_lifecycles?: CanvasComponentLifecycle[];
}
/**
@@ -17223,6 +17253,34 @@ export namespace Schemas {
created_at: string;
}
+ /**
+ * Everything a client needs to open a canvas, in one round trip.
+ *
+ * Replaces the record → builds → source waterfall: the record, the live
+ * build (with its signed artifact URL), and — only when there is nothing
+ * built to render — the head source project (freeform/component) or the
+ * layout document (grid).
+ */
+ export interface CanvasViewResponse {
+ /** The canvas record. */
+ canvas: Canvas;
+ /** The live build with its signed artifact URL. Null until a build completes. */
+ published_build: CanvasBuild | null;
+ /**
+ * Id of the source version the canvas's head points at. Null before the first publish.
+ * @nullable
+ */
+ current_version_id: string | null;
+ /** True while a build is queued or running — poll the builds endpoint until it settles. */
+ has_active_build: boolean;
+ /** The head source project, present only when the canvas has no live build to render (the client-side fallback tier). Null otherwise, and always null for grid canvases. */
+ source?: CanvasSourceProject | null;
+ /** For grid canvases: the head layout document. Null for other kinds. */
+ layout?: CanvasLayout | null;
+ /** For grid canvases: the renderable build of every component the layout's live placements reference, so the grid renders from this one call. Absent for other kinds. */
+ component_lifecycles?: CanvasComponentLifecycle[];
+ }
+
export interface CapabilityReadiness {
/** cost/attribution/roas/cac */
capability: string;
@@ -94606,6 +94664,10 @@ export namespace Schemas {
} as const;
export type CanvasesBuildsRetrieveParams = {
+ /**
+ * "slim" returns only what rendering needs — the live build, the head version's builds, and anything still in flight — instead of the full recent-build history. Any other value (or none) returns the full window.
+ */
+ scope?: string;
/**
* Include the retained ready build for this historical source version.
*/
@@ -94624,6 +94686,10 @@ export namespace Schemas {
};
export type CanvasesLayoutRetrieveParams = {
+ /**
+ * Also return the renderable build (with signed artifact URL) of every component the layout's live placements reference, so a grid renders from this one call.
+ */
+ include_components?: boolean;
/**
* Read this historical layout version instead of the head (for version browsing).
*/
diff --git a/services/mcp/src/generated/canvas/api.ts b/services/mcp/src/generated/canvas/api.ts
index 47e16086b26d..3412e3e222d0 100644
--- a/services/mcp/src/generated/canvas/api.ts
+++ b/services/mcp/src/generated/canvas/api.ts
@@ -114,7 +114,8 @@ export const CanvasesPartialUpdateBody = () => zod
*
* A publish queues a build; poll this until it is ready (the live pointer
* advances) or failed (fix the error diagnostics and publish again — the
- * last good build stays live).
+ * last good build stays live). Send the response's ETag back as
+ * If-None-Match to make the poll revalidate without a body.
*/
export const CanvasesBuildsRetrieveParams = () => zod.object({
id: zod.string().describe('A UUID string identifying this canvas.'),
@@ -126,6 +127,12 @@ export const CanvasesBuildsRetrieveParams = () => zod.object({
})
export const CanvasesBuildsRetrieveQueryParams = () => zod.object({
+ scope: zod
+ .string()
+ .optional()
+ .describe(
+ '\"slim\" returns only what rendering needs — the live build, the head version\'s builds, and anything still in flight — instead of the full recent-build history. Any other value (or none) returns the full window.'
+ ),
version_id: zod
.string()
.optional()
@@ -487,6 +494,12 @@ export const CanvasesLayoutRetrieveParams = () => zod.object({
})
export const CanvasesLayoutRetrieveQueryParams = () => zod.object({
+ include_components: zod
+ .boolean()
+ .optional()
+ .describe(
+ "Also return the renderable build (with signed artifact URL) of every component the layout's live placements reference, so a grid renders from this one call."
+ ),
version_id: zod
.string()
.optional()
diff --git a/services/mcp/src/tools/generated/canvas.ts b/services/mcp/src/tools/generated/canvas.ts
index 02a4f59243c3..c5b9dea62ca0 100644
--- a/services/mcp/src/tools/generated/canvas.ts
+++ b/services/mcp/src/tools/generated/canvas.ts
@@ -25,6 +25,7 @@ const canvasBuildsRetrieve = (): ToolBase<
method: 'GET',
path: `/api/projects/${encodeURIComponent(String(projectId))}/canvases/${encodeURIComponent(String(params.id))}/builds/`,
query: {
+ scope: params.scope,
version_id: params.version_id,
},
})
@@ -201,19 +202,28 @@ const canvasEditCreate = (): ToolBase<
const CanvasLayoutGetSchema = () => {
const CanvasesLayoutRetrieveParams = orvalSchemas.CanvasesLayoutRetrieveParams()
- return CanvasesLayoutRetrieveParams.omit({ project_id: true }).extend({
- id: CanvasesLayoutRetrieveParams.shape['id'].describe('ID of the grid canvas whose layout to read.'),
- })
+ const CanvasesLayoutRetrieveQueryParams = orvalSchemas.CanvasesLayoutRetrieveQueryParams()
+ return CanvasesLayoutRetrieveParams.omit({ project_id: true })
+ .extend(CanvasesLayoutRetrieveQueryParams.omit({ version_id: true }).shape)
+ .extend({
+ id: CanvasesLayoutRetrieveParams.shape['id'].describe('ID of the grid canvas whose layout to read.'),
+ })
}
-const canvasLayoutGet = (): ToolBase<ReturnType<typeof CanvasLayoutGetSchema>, Schemas.CanvasLayoutResponse> => ({
+const canvasLayoutGet = (): ToolBase<
+ ReturnType<typeof CanvasLayoutGetSchema>,
+ Schemas.CanvasLayoutWithComponentsResponse
+> => ({
name: 'canvas-layout-get',
schema: CanvasLayoutGetSchema(),
handler: async (context: Context, params: z.infer<ReturnType<typeof CanvasLayoutGetSchema>>) => {
const projectId = await context.stateManager.getProjectId()
- const result = await context.api.request<Schemas.CanvasLayoutResponse>({
+ const result = await context.api.request<Schemas.CanvasLayoutWithComponentsResponse>({
method: 'GET',
path: `/api/projects/${encodeURIComponent(String(projectId))}/canvases/${encodeURIComponent(String(params.id))}/layout/`,
+ query: {
+ include_components: params.include_components,
+ },
})
return result
},
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-builds-retrieve.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-builds-retrieve.json
index 946f07abfdbe..69c3c85d7a7d 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-builds-retrieve.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-builds-retrieve.json
@@ -5,6 +5,10 @@
"description": "ID of the canvas whose builds to read.",
"type": "string"
},
+ "scope": {
+ "description": "\"slim\" returns only what rendering needs — the live build, the head version's builds, and anything still in flight — instead of the full recent-build history. Any other value (or none) returns the full window.",
+ "type": "string"
+ },
"version_id": {
"description": "Include the retained ready build for this historical source version.",
"type": "string"
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-layout-get.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-layout-get.json
index 1aadab4a45c0..7b50d34f8fc9 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-layout-get.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/canvas-layout-get.json
@@ -4,6 +4,10 @@
"id": {
"description": "ID of the grid canvas whose layout to read.",
"type": "string"
+ },
+ "include_components": {
+ "description": "Also return the renderable build (with signed artifact URL) of every component the layout's live placements reference, so a grid renders from this one call.",
+ "type": "boolean"
}
},
"required": ["id"],