: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): add the ph.state key-value store backend (#82918)
Peter Kirkhame3cab07107ee
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex 81e69575a7c7..325b498a1f84 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -88,6 +88,7 @@ rules:|Canvas|CanvasBuild|CanvasSourceVersion+ |CanvasState|ChangeRequest|ChannelContextGeneration|ChannelInstructions@@ -451,6 +452,7 @@ rules:|Canvas|CanvasBuild|CanvasSourceVersion+ |CanvasState|ChangeRequest|ChannelContextGeneration|ChannelInstructionsdiff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 106c05179650..532da8e3026a 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -678,6 +678,8 @@ SPECTACULAR_SETTINGS = {"TargetTypeEnum": "products.exports.backend.models.subscription.Subscription.SubscriptionTarget",# --- Inline value lists (type-hint enums, no x-spec-enum-id) ---"PropertyGroupOperator": ["AND", "OR"],+ # `scope`/`state` are generic field names; one shared name for the canvas state scope set.+ "CanvasStateScopeEnum": ["user", "shared"],# `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/annotations/backend/facade/__init__.py b/products/annotations/backend/facade/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/annotations/backend/facade/api.py b/products/annotations/backend/facade/api.pynew file mode 100644index 000000000000..e261bb4910b0--- /dev/null+++ b/products/annotations/backend/facade/api.py@@ -0,0 +1,35 @@+"""Facade API for the annotations product — the surface other products may import.++Thin by design: accept ids, return ids, never ORM instances.+"""++from datetime import datetime++from django.utils import timezone++from posthog.models import Team++from products.annotations.backend.models.annotation import Annotation++__all__ = ["create_project_annotation"]+++def create_project_annotation(+ team_id: int, user_id: int | None, *, content: str, date_marker: datetime | None = None+) -> int:+ """Create a project-scoped annotation as the user, returning its id.++ ``date_marker`` defaults to the creation time when omitted — a null marker+ would keep the annotation off every chart and out of AI context, which is+ never what a project annotation wants.+ """+ team = Team.objects.get(id=team_id)+ annotation = Annotation.objects.create(+ team_id=team_id,+ organization_id=team.organization_id,+ created_by_id=user_id,+ content=content,+ date_marker=date_marker if date_marker is not None else timezone.now(),+ scope=Annotation.Scope.PROJECT,+ )+ return annotation.iddiff --git a/products/canvas/backend/actions.py b/products/canvas/backend/actions.pynew file mode 100644index 000000000000..f51597f33b2a--- /dev/null+++ b/products/canvas/backend/actions.py@@ -0,0 +1,149 @@+"""Canvas action registry: the PostHog writes a canvas may invoke (ph.actions).++One pipeline serves every verb: the host forwards ph.actions.invoke(verb,+payload) to the invoke endpoint, which checks the canvas's declared+capabilities, validates the payload against the verb's serializer, and+executes as the viewer — the server re-checks the viewer's own permissions,+exactly as if they acted in the app. Adding a verb is a registry entry, not a+design. Verbs that delete or disable set ``destructive=True``, which the host+renders as an explicit confirm before invoking.++Executors import their product facades lazily so this module stays cheap on+the source-validation import path (the builder imports it for verb names).+"""++from collections.abc import Callable+from typing import TYPE_CHECKING, Any++import structlog+import posthoganalytics+from rest_framework import serializers++from posthog.dataclasses import frozen++if TYPE_CHECKING:+ from posthog.models import Team++ from products.canvas.backend.models import Canvas++logger = structlog.get_logger(__name__)++# Kill switch: enabling this flag for a team turns every action verb off at+# once. Evaluation failure leaves actions on — the switch is for emergencies,+# not a gate normal traffic should wait on.+CANVAS_ACTIONS_KILL_SWITCH_FLAG = "canvas-actions-disabled"+++def canvas_actions_disabled(team: "Team") -> bool:+ try:+ return bool(+ posthoganalytics.feature_enabled(+ CANVAS_ACTIONS_KILL_SWITCH_FLAG,+ str(team.uuid),+ only_evaluate_locally=False,+ send_feature_flag_events=False,+ )+ )+ except Exception:+ logger.exception("canvas_actions_kill_switch_check_failed")+ return False+++class AnnotationCreatePayloadSerializer(serializers.Serializer):+ """Payload for the annotations.create verb."""++ content = serializers.CharField(max_length=1024, help_text="The annotation text.")+ date_marker = serializers.DateTimeField(+ required=False,+ allow_null=True,+ default=None,+ help_text="Point in time the annotation marks. Omit to mark the moment it was created.",+ )+++class TaskCreatePayloadSerializer(serializers.Serializer):+ """Payload for the tasks.create verb."""++ title = serializers.CharField(max_length=255, help_text="Task title (max 255 characters, matching the task store).")+ description = serializers.CharField(+ allow_blank=True, default="", help_text="Task description (markdown), passed to the agent that picks it up."+ )+++def _create_annotation(team_id: int, user_id: int, canvas: "Canvas", payload: dict[str, Any]) -> dict[str, Any]:+ from products.annotations.backend.facade import api as annotations_facade # noqa: PLC0415 — load on execute++ annotation_id = annotations_facade.create_project_annotation(+ team_id, user_id, content=payload["content"], date_marker=payload.get("date_marker")+ )+ return {"annotation_id": annotation_id}+++def _create_task(team_id: int, user_id: int, canvas: "Canvas", payload: dict[str, Any]) -> dict[str, Any]:+ from products.tasks.backend.facade import api as tasks_facade # noqa: PLC0415 — load on execute++ task_id = tasks_facade.create_channel_task(+ team_id, user_id, canvas.channel_id, title=payload["title"], description=payload["description"]+ )+ return {"task_id": str(task_id)}+++@frozen+class CanvasAction:+ """One verb of the registry: what it does, its payload shape, and how loudly the host must ask."""++ verb: str+ summary: str+ destructive: bool+ payload_serializer: type[serializers.Serializer]+ execute: Callable[[int, int, "Canvas", dict[str, Any]], dict[str, Any]]+ # API scopes a scoped credential (personal API key, OAuth token) must hold+ # to invoke this verb — the target resource's write scope, so canvas:write+ # alone never grants writes to other resources. Session users carry no+ # scopes and are unaffected.+ required_scopes: tuple[str, ...]+ # Authoring docs served through the registry endpoint: payload and result+ # shape, what actually happens, and the confirmation copy the verb+ # warrants. Agents build against the deployed registry rather than a skill+ # file, so a verb's docs ship (and stay current) with the verb itself.+ usage: str+++CANVAS_ACTIONS: dict[str, CanvasAction] = {+ action.verb: action+ for action in [+ CanvasAction(+ verb="annotations.create",+ summary="Create a project annotation.",+ destructive=False,+ payload_serializer=AnnotationCreatePayloadSerializer,+ execute=_create_annotation,+ required_scopes=("annotation:write",),+ usage=(+ "Payload `{content, date_marker?}` → result `{annotation_id}`. Creates a project "+ "annotation: a note pinned to a point in time, rendered as a marker on insight "+ "graphs and listed under Data management → Annotations. Pass `date_marker` (ISO "+ "timestamp) when the moment is not now — e.g. when an incident started, not when "+ "it was written down. `content` is capped at 1024 characters."+ ),+ ),+ CanvasAction(+ verb="tasks.create",+ summary="File a task in the canvas's channel, as the viewer.",+ destructive=False,+ payload_serializer=TaskCreatePayloadSerializer,+ execute=_create_task,+ required_scopes=("task:write",),+ usage=(+ "Payload `{title, description}` → result `{task_id}`. Files a bare task into the "+ "canvas's own channel, created by the viewer — it appears in the channel feed "+ "under their name. No agent run starts and no repository or run configuration is "+ "attached; the viewer opens it from the channel and drives it from there. Say that "+ 'in the confirmation copy ("Task filed in this channel — open it to start work"), '+ 'never "an agent is on it". Keep the title short and put full context in '+ "`description` (markdown) — whoever picks the task up sees only those two fields, "+ "not the canvas."+ ),+ ),+ ]+}diff --git a/products/canvas/backend/capabilities.py b/products/canvas/backend/capabilities.pyindex cf02b0501601..405e73a49971 100644--- a/products/canvas/backend/capabilities.py+++ b/products/canvas/backend/capabilities.py@@ -18,6 +18,16 @@ def _network_origins(manifest: dict | None) -> list[str]:return ((manifest or {}).get("network") or {}).get("origins") or []+def declared_state_scopes(manifest: dict | None) -> set[str]:+ """The ph.state scopes a capabilities manifest declares."""+ return set(_posthog_section(manifest).get("state") or [])+++def declared_actions(manifest: dict | None) -> set[str]:+ """The ph.actions verbs a capabilities manifest declares."""+ return set(_posthog_section(manifest).get("actions") or [])++@dataclass(frozen=True, kw_only=True)class CapabilityWidening:"""What `after` declares beyond `before`. Narrowings are not reported here@@ -28,6 +38,8 @@ class CapabilityWidening:capture_events_added: list[str]inline_queries_enabled: boolnetwork_origins_added: list[str]+ state_scopes_added: list[str]+ actions_added: list[str]@propertydef widens(self) -> bool:@@ -36,6 +48,8 @@ class CapabilityWidening:or self.capture_events_addedor self.inline_queries_enabledor self.network_origins_added+ or self.state_scopes_added+ or self.actions_added)@@ -55,4 +69,6 @@ def capability_widening(before: dict | None, after: dict | None) -> CapabilityWi),inline_queries_enabled=bool(after_ph.get("inlineQueries")) and not bool(before_ph.get("inlineQueries")),network_origins_added=sorted(set(_network_origins(after)) - set(_network_origins(before))),+ state_scopes_added=sorted(set(after_ph.get("state") or []) - set(before_ph.get("state") or [])),+ actions_added=sorted(set(after_ph.get("actions") or []) - set(before_ph.get("actions") or [])),)diff --git a/products/canvas/backend/migrations/0011_canvasstate.py b/products/canvas/backend/migrations/0011_canvasstate.pynew file mode 100644index 000000000000..2027a34d3b18--- /dev/null+++ b/products/canvas/backend/migrations/0011_canvasstate.py@@ -0,0 +1,79 @@+# Generated by Django 5.2.17 on 2026-08-13 20:39++import django.utils.timezone+import django.db.models.deletion+from django.conf import settings+from django.db import migrations, models++import posthog.uuidt+++class Migration(migrations.Migration):+ dependencies = [+ ("canvas", "0010_canvassourceversion_draft"),+ ("posthog", "1300_identityproviderconfig_saml_relay_state_unique"),+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ]++ operations = [+ migrations.CreateModel(+ name="CanvasState",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.uuidt.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("scope", models.CharField(max_length=8)),+ ("key", models.CharField(max_length=200)),+ ("value", models.JSONField()),+ ("created_at", models.DateTimeField(default=django.utils.timezone.now)),+ ("updated_at", models.DateTimeField(auto_now=True)),+ (+ "canvas",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="state_entries",+ to="canvas.canvas",+ ),+ ),+ (+ "team",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ to="posthog.team",+ ),+ ),+ (+ "user",+ models.ForeignKey(+ blank=True,+ db_constraint=False,+ null=True,+ on_delete=django.db.models.deletion.CASCADE,+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ ],+ options={+ "db_table": "posthog_canvas_state",+ "constraints": [+ models.UniqueConstraint(+ condition=models.Q(("user__isnull", False)),+ fields=("canvas", "scope", "user", "key"),+ name="canvas_state_user_key",+ ),+ models.UniqueConstraint(+ condition=models.Q(("user__isnull", True)),+ fields=("canvas", "scope", "key"),+ name="canvas_state_shared_key",+ ),+ ],+ },+ ),+ ]diff --git a/products/canvas/backend/migrations/max_migration.txt b/products/canvas/backend/migrations/max_migration.txtindex 8ef21ba2c32e..0894d328c1f6 100644--- a/products/canvas/backend/migrations/max_migration.txt+++ b/products/canvas/backend/migrations/max_migration.txt@@ -1 +1 @@-0010_canvassourceversion_draft+0011_canvasstatediff --git a/products/canvas/backend/models.py b/products/canvas/backend/models.pyindex 9969f7a244e2..49ec2d464021 100644--- a/products/canvas/backend/models.py+++ b/products/canvas/backend/models.py@@ -160,3 +160,44 @@ class CanvasBuild(TeamScopedRootMixin, UUIDModel):name="canvas_build_retention",),]+++class CanvasState(TeamScopedRootMixin, UUIDModel):+ """One key of a canvas's runtime key-value store (the ``ph.state`` verb).++ ``user`` rows belong to one viewer; ``shared`` rows to the canvas itself.+ Values are application data written from viewer sessions — never secrets —+ and bounded at write time (value size, keys per scope), which keeps every+ access a point lookup and table growth capped by canvas count.+ """++ SCOPE_USER = "user"+ SCOPE_SHARED = "shared"+ SCOPES = [SCOPE_USER, SCOPE_SHARED]++ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)+ canvas = models.ForeignKey(Canvas, on_delete=models.CASCADE, related_name="state_entries")+ scope = models.CharField(max_length=8)+ # The owning viewer for user-scoped rows; always null for shared rows.+ user = models.ForeignKey("posthog.User", on_delete=models.CASCADE, null=True, blank=True, db_constraint=False)+ key = models.CharField(max_length=200)+ value = models.JSONField()+ created_at = models.DateTimeField(default=timezone.now)+ updated_at = models.DateTimeField(auto_now=True)++ class Meta:+ db_table = "posthog_canvas_state"+ constraints = [+ # Postgres treats NULLs as distinct, so shared rows (user NULL) get+ # their own uniqueness arm instead of one four-column constraint.+ models.UniqueConstraint(+ fields=["canvas", "scope", "user", "key"],+ condition=Q(user__isnull=False),+ name="canvas_state_user_key",+ ),+ models.UniqueConstraint(+ fields=["canvas", "scope", "key"],+ condition=Q(user__isnull=True),+ name="canvas_state_shared_key",+ ),+ ]diff --git a/products/canvas/backend/presentation/serializers.py b/products/canvas/backend/presentation/serializers.pyindex f00b7880c071..45b2e857f135 100644--- a/products/canvas/backend/presentation/serializers.py+++ b/products/canvas/backend/presentation/serializers.py@@ -7,7 +7,7 @@ from rest_framework import serializersfrom posthog.api.shared import UserBasicSerializerfrom products.canvas.backend.contract import canvas_sdk_version, contract_limits-from products.canvas.backend.models import Canvas+from products.canvas.backend.models import Canvas, CanvasState# Base64 expands 3 source bytes into 4 characters (padded); size the asset field# from the contract's total-source cap rather than restating the number.@@ -132,6 +132,28 @@ class CanvasPostHogCapabilitiesSerializer(serializers.Serializer):insights = serializers.ListField(child=serializers.CharField(max_length=128), max_length=100)inlineQueries = serializers.BooleanField()captureEvents = serializers.ListField(child=serializers.CharField(max_length=200), max_length=100)+ # Optional so projects published before the state store exist unchanged.+ state = serializers.ListField(+ child=serializers.ChoiceField(choices=CanvasState.SCOPES),+ required=False,+ default=list,+ max_length=2,+ help_text=(+ "State scopes the canvas may use via ph.state: 'user' (private to each viewer) "+ "and/or 'shared' (one value per canvas, team-visible)."+ ),+ )+ # Optional so projects published before the action registry exist unchanged.+ actions = serializers.ListField(+ child=serializers.CharField(max_length=64),+ required=False,+ default=list,+ max_length=32,+ help_text=(+ "Registered action verbs the canvas may invoke via ph.actions (e.g. 'annotations.create', "+ "'tasks.create'). Each executes as the viewer; declaring one shows it in the promote review."+ ),+ )class CanvasNetworkCapabilitiesSerializer(serializers.Serializer):@@ -179,7 +201,7 @@ class CanvasSourceProjectSerializer(serializers.Serializer):capabilities = CanvasCapabilitiesSerializer(required=False,default=lambda: {- "posthog": {"insights": [], "inlineQueries": False, "captureEvents": []},+ "posthog": {"insights": [], "inlineQueries": False, "captureEvents": [], "state": [], "actions": []},"network": {"origins": []},},help_text=(@@ -558,6 +580,88 @@ class CanvasCapabilityWideningSerializer(serializers.Serializer):child=serializers.CharField(),help_text="Network origins the draft newly declares it may reach.",)+ state_scopes_added = serializers.ListField(+ child=serializers.CharField(),+ help_text="State scopes (user, shared) the draft newly declares for ph.state.",+ )+ actions_added = serializers.ListField(+ child=serializers.CharField(),+ help_text="Action verbs the draft newly declares it may invoke via ph.actions.",+ )+++class CanvasActionDefinitionSerializer(serializers.Serializer):+ """One registered action verb, as the host renders it before invoking."""++ verb = serializers.CharField(help_text="The verb's registry name, e.g. 'annotations.create'.")+ summary = serializers.CharField(help_text="One line naming what invoking the verb does.")+ destructive = serializers.BooleanField(+ help_text="True when the verb deletes or disables something; the host must confirm with the viewer first."+ )+ usage = serializers.CharField(+ help_text="Authoring docs for the verb: payload and result shape, behavior, and the confirmation copy it warrants."+ )+++class CanvasActionsResponseSerializer(serializers.Serializer):+ """The action registry: every verb a canvas may declare and invoke."""++ actions = CanvasActionDefinitionSerializer(many=True, help_text="Registered verbs, sorted by name.")+++class CanvasActionInvokeSerializer(serializers.Serializer):+ """Payload for invoking one action verb."""++ verb = serializers.CharField(max_length=64, help_text="Registered verb to invoke, e.g. 'tasks.create'.")+ payload = serializers.DictField(+ required=False,+ default=dict,+ help_text="Verb-specific arguments, validated against the verb's payload schema.",+ )+++class CanvasActionResultSerializer(serializers.Serializer):+ """Result of one action invocation."""++ verb = serializers.CharField(help_text="The verb that executed.")+ result = serializers.DictField(+ help_text="Verb-specific result, e.g. {'task_id': ...} for tasks.create.",+ )+++class CanvasStateEntrySerializer(serializers.Serializer):+ """One key of a canvas's runtime key-value state (the ph.state store)."""++ scope = serializers.ChoiceField(+ choices=CanvasState.SCOPES,+ help_text="user: private to the viewer who wrote it. shared: one value per canvas, visible to every viewer.",+ )+ key = serializers.CharField(max_length=200, help_text="The entry's key, unique within its scope.")+ value = serializers.JSONField(help_text="The stored JSON value.")+ updated_at = serializers.DateTimeField(help_text="When the entry was last written.")+++class CanvasStateResponseSerializer(serializers.Serializer):+ """The canvas state readable by the caller."""++ entries = CanvasStateEntrySerializer(+ many=True,+ help_text="The canvas's shared entries plus the caller's own user-scoped entries.",+ )+++class CanvasStateSetSerializer(serializers.Serializer):+ """Payload for writing (or deleting) one key of a canvas's runtime state."""++ scope = serializers.ChoiceField(+ choices=CanvasState.SCOPES,+ help_text="Scope to write into; the canvas must declare it in capabilities.posthog.state.",+ )+ key = serializers.CharField(max_length=200, help_text="Key to write, unique within its scope.")+ value = serializers.JSONField(+ allow_null=True,+ help_text="JSON value to store (at most 64 KB serialized), or null to delete the key.",+ )class CanvasSourceDraftResponseSerializer(serializers.Serializer):diff --git a/products/canvas/backend/presentation/views.py b/products/canvas/backend/presentation/views.pyindex ef02c54bb290..35920ec637a8 100644--- a/products/canvas/backend/presentation/views.py+++ b/products/canvas/backend/presentation/views.py@@ -1,7 +1,9 @@+import jsonfrom typing import Any, castfrom uuid import UUIDfrom django.core.exceptions import ValidationError as DjangoValidationError+from django.db import transactionfrom django.db.models import Q, QuerySetfrom django.utils import timezone@@ -12,6 +14,7 @@ from rest_framework.decorators import actionfrom rest_framework.exceptions import NotFoundfrom rest_framework.request import Requestfrom rest_framework.response import Response+from rest_framework.throttling import BaseThrottle, SimpleRateThrottlefrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.auth import OAuthAccessTokenAuthentication@@ -23,8 +26,14 @@ from posthog.storage.object_storage import ObjectStorageErrorfrom posthog.temporal.oauth import SANDBOX_OAUTH_APP_CLIENT_IDSfrom products.canvas.backend import build_service, error_reports-from products.canvas.backend.models import Canvas, CanvasBuild, CanvasSourceVersion+from products.canvas.backend.actions import CANVAS_ACTIONS, canvas_actions_disabled+from products.canvas.backend.capabilities import declared_actions, declared_state_scopes+from products.canvas.backend.contract import contract_limits+from products.canvas.backend.models import Canvas, CanvasBuild, CanvasSourceVersion, CanvasStatefrom products.canvas.backend.presentation.serializers import (+ CanvasActionInvokeSerializer,+ CanvasActionResultSerializer,+ CanvasActionsResponseSerializer,CanvasBuildActionSerializer,CanvasBuildSerializer,CanvasBuildsResponseSerializer,@@ -47,6 +56,9 @@ from products.canvas.backend.presentation.serializers import (CanvasSourcePublishResponseSerializer,CanvasSourcePublishSerializer,CanvasSourceResponseSerializer,+ CanvasStateEntrySerializer,+ CanvasStateResponseSerializer,+ CanvasStateSetSerializer,CanvasSummarySerializer,CanvasUpdateSerializer,CanvasValidateRequestSerializer,@@ -62,6 +74,11 @@ from products.tasks.backend.facade import api as tasks_facadeBUILDS_WINDOW = 20# Version-history window for the client's undo/revert browser.VERSIONS_WINDOW = 100+# Write-time bounds on canvas runtime state (ph.state), from the platform+# contract so the desktop bridge mirrors them instead of restating numbers.+# They keep every access a point lookup and cap table growth by canvas count.+CANVAS_STATE_MAX_VALUE_BYTES = contract_limits()["maxStateValueBytes"]+CANVAS_STATE_MAX_KEYS_PER_SCOPE = contract_limits()["maxStateKeysPerScope"]def _capacity_response() -> Response:@@ -94,6 +111,33 @@ def _invalid_response(diagnostics: list[dict[str, Any]]) -> Response:)+def _state_rejection() -> Response:+ return Response(+ {"detail": "Canvas state is a viewer surface; sandbox tokens cannot use it."},+ status=status.HTTP_403_FORBIDDEN,+ )+++class CanvasStateWriteThrottle(SimpleRateThrottle):+ """Per viewer per canvas. State writes are interaction-driven app data, so+ the ceiling is generous — it exists to stop a canvas render loop from+ hammering the table, not to meter normal use."""++ scope = "canvas_state_write"+ rate = "240/min"++ def get_cache_key(self, request: Request, view: Any) -> str:+ ident = request.user.pk if request.user and request.user.is_authenticated else self.get_ident(request)+ return self.cache_format % {"scope": self.scope, "ident": f"{ident}:{view.kwargs.get('pk')}"}+++class CanvasActionInvokeThrottle(CanvasStateWriteThrottle):+ """Tighter than state writes: every invocation is a real PostHog write."""++ scope = "canvas_action_invoke"+ rate = "60/min"++class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):"""Canvases: agent-built sandboxed browser apps, filed into channels.@@ -107,7 +151,7 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):queryset = Canvas.objects.unscoped().select_related("created_by")serializer_class = CanvasSerializerhttp_method_names = ["get", "post", "patch", "delete", "head", "options"]- scope_object_read_actions = ["list", "retrieve", "source", "versions", "drafts", "builds", "validate"]+ scope_object_read_actions = ["list", "retrieve", "source", "versions", "drafts", "builds", "validate", "state"]scope_object_write_actions = ["create","partial_update",@@ -121,8 +165,31 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):"build_action","report_error","request_fix",+ "set_state",+ "invoke_action",]+ def get_throttles(self) -> list[BaseThrottle]:+ # On top of the defaults, not instead of them: the per-canvas key must+ # not let a caller rotate canvases past the project-wide limits.+ if self.action == "set_state":+ return [*super().get_throttles(), CanvasStateWriteThrottle()]+ if self.action == "invoke_action":+ return [*super().get_throttles(), CanvasActionInvokeThrottle()]+ return super().get_throttles()++ def dangerously_get_required_scopes(self, request: Request, view: Any) -> list[str] | None:+ # Invoking a verb writes the target resource, so a scoped credential+ # must hold that resource's scope — canvas:write alone is not consent+ # to create tasks or annotations.+ if getattr(view, "action", None) != "invoke_action":+ return None+ verb = request.data.get("verb") if isinstance(request.data, dict) else None+ entry = CANVAS_ACTIONS.get(verb) if isinstance(verb, str) else None+ if entry is None:+ return None+ return ["canvas:write", *entry.required_scopes]+_CREATOR_ONLY_ACTIONS = {"partial_update","destroy",@@ -997,6 +1064,211 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):raise NotFound("Build not found for this canvas.")return build+ def _state_actor(self, request: Request) -> User | None:+ """The viewer whose state is read or written; None rejects the call.++ Sandboxes are excluded by design: runtime state belongs to viewer+ sessions, and the authoring agent works with it through the source+ code it publishes, not by writing rows.+ """+ if self._is_sandbox_authenticated(request):+ return None+ return self._request_user()++ @extend_schema(+ operation_id="canvases_actions_retrieve",+ responses={200: CanvasActionsResponseSerializer},+ )+ @action(methods=["GET"], detail=False, url_path="actions")+ def actions(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """List the action registry: every verb a canvas may declare and invoke."""+ rows = [+ {"verb": entry.verb, "summary": entry.summary, "destructive": entry.destructive, "usage": entry.usage}+ for entry in sorted(CANVAS_ACTIONS.values(), key=lambda entry: entry.verb)+ ]+ return Response(CanvasActionsResponseSerializer(instance={"actions": rows}).data)++ @extend_schema(+ operation_id="canvases_actions_invoke",+ request=CanvasActionInvokeSerializer,+ responses={+ 200: CanvasActionResultSerializer,+ 400: OpenApiResponse(description="Unknown verb, or the payload failed the verb's schema."),+ 403: OpenApiResponse(+ description="The verb is not declared in the canvas's capabilities, actions are disabled for the "+ "team, or the caller is a sandbox."+ ),+ },+ )+ @action(methods=["POST"], detail=True, url_path="actions/invoke")+ def invoke_action(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """Invoke one registered action verb as the viewer.++ The canvas must declare the verb in capabilities.posthog.actions (the+ reviewed permission boundary); the write itself runs with the viewer's+ own permissions, exactly as if they acted in the app.+ """+ canvas = self.get_object()+ user = self._state_actor(request)+ if user is None:+ return Response(+ {"detail": "Canvas actions are invoked by viewers; sandbox tokens cannot use them."},+ status=status.HTTP_403_FORBIDDEN,+ )+ if canvas_actions_disabled(self.team):+ return Response(+ {"detail": "Canvas actions are disabled for this team."},+ status=status.HTTP_403_FORBIDDEN,+ )+ payload = CanvasActionInvokeSerializer(data=request.data)+ payload.is_valid(raise_exception=True)+ verb = payload.validated_data["verb"]+ entry = CANVAS_ACTIONS.get(verb)+ if entry is None:+ return Response(+ {"detail": f'Unknown action verb "{verb}". Registered verbs: {", ".join(sorted(CANVAS_ACTIONS))}.'},+ status=status.HTTP_400_BAD_REQUEST,+ )+ version = canvas.current_source_version+ if verb not in declared_actions(version.capabilities if version else None):+ return Response(+ {+ "detail": f'The canvas does not declare action "{verb}". '+ "Add it to capabilities.posthog.actions and publish."+ },+ status=status.HTTP_403_FORBIDDEN,+ )+ verb_payload = entry.payload_serializer(data=payload.validated_data["payload"])+ verb_payload.is_valid(raise_exception=True)+ try:+ result = entry.execute(self.team_id, user.id, canvas, verb_payload.validated_data)+ except ValueError as error:+ return Response({"detail": str(error)}, status=status.HTTP_400_BAD_REQUEST)+ # Every execution is audited: the trigger names the verb, the activity+ # log row names the viewer it ran as.+ self._log_canvas_activity(+ canvas,+ "action_invoked",+ Detail(+ name=canvas.name,+ trigger=Trigger(job_type="canvas_action", job_id=verb, payload={"verb": verb}),+ ),+ )+ self._report_canvas_action("canvas action invoked", canvas, verb=verb)+ return Response(CanvasActionResultSerializer(instance={"verb": verb, "result": result}).data)++ @extend_schema(+ operation_id="canvases_state_retrieve",+ parameters=[+ OpenApiParameter(+ "scope",+ OpenApiTypes.STR,+ required=False,+ enum=CanvasState.SCOPES,+ description="Only return entries in this scope.",+ )+ ],+ responses={+ 200: CanvasStateResponseSerializer,+ 403: OpenApiResponse(description="Canvas state is a viewer surface; sandbox tokens cannot use it."),+ },+ )+ @action(methods=["GET"], detail=True)+ def state(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """Read the canvas's runtime key-value state (the ph.state store).++ Returns the canvas's shared entries plus the caller's own user-scoped+ entries — never another viewer's.+ """+ canvas = self.get_object()+ user = self._state_actor(request)+ if user is None:+ return _state_rejection()+ # Reads honor the same reviewed boundary as writes: a canvas only sees+ # the scopes its head version declares, so narrowing capabilities also+ # stops reads of previously written entries.+ version = canvas.current_source_version+ declared = declared_state_scopes(version.capabilities if version else None)+ entries = (+ CanvasState.objects.for_team(self.team_id)+ .filter(canvas=canvas, scope__in=declared)+ .filter(Q(scope=CanvasState.SCOPE_SHARED, user__isnull=True) | Q(scope=CanvasState.SCOPE_USER, user=user))+ )+ scope = request.query_params.get("scope")+ if scope:+ if scope not in CanvasState.SCOPES:+ return Response({"detail": "scope must be 'user' or 'shared'."}, status=status.HTTP_400_BAD_REQUEST)+ entries = entries.filter(scope=scope)+ return Response(CanvasStateResponseSerializer(instance={"entries": entries.order_by("scope", "key")}).data)++ @extend_schema(+ operation_id="canvases_state_set",+ request=CanvasStateSetSerializer,+ responses={+ 200: CanvasStateEntrySerializer,+ 204: OpenApiResponse(description="The key was deleted (value was null)."),+ 400: OpenApiResponse(description="The value or the scope's key count exceeds the state bounds."),+ 403: OpenApiResponse(+ description="The scope is not declared in the canvas's capabilities, or the caller is a sandbox."+ ),+ },+ )+ @action(methods=["POST"], detail=True, url_path="state/set")+ def set_state(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """Write one key of the canvas's runtime state, or delete it with a null value."""+ canvas = self.get_object()+ user = self._state_actor(request)+ if user is None:+ return _state_rejection()+ payload = CanvasStateSetSerializer(data=request.data)+ payload.is_valid(raise_exception=True)+ scope = payload.validated_data["scope"]+ key = payload.validated_data["key"]+ value = payload.validated_data["value"]+ # The head version's declared capabilities gate writes: state is part of+ # the canvas's reviewed permission boundary, exactly like insights.+ version = canvas.current_source_version+ declared = declared_state_scopes(version.capabilities if version else None)+ if scope not in declared:+ return Response(+ {+ "detail": f'The canvas does not declare state scope "{scope}". '+ "Add it to capabilities.posthog.state and publish."+ },+ status=status.HTTP_403_FORBIDDEN,+ )+ owner = user if scope == CanvasState.SCOPE_USER else None+ scoped = CanvasState.objects.for_team(self.team_id).filter(canvas=canvas, scope=scope, user=owner)+ existing = scoped.filter(key=key)+ if value is None:+ existing.delete()+ return Response(status=status.HTTP_204_NO_CONTENT)+ if len(json.dumps(value, separators=(",", ":")).encode()) > CANVAS_STATE_MAX_VALUE_BYTES:+ return Response(+ {+ "detail": f"State values are capped at {CANVAS_STATE_MAX_VALUE_BYTES // 1024} KB serialized. "+ "Store large data in PostHog (insights, the warehouse) and reference it."+ },+ status=status.HTTP_400_BAD_REQUEST,+ )+ with transaction.atomic():+ # The canvas row is the mutex for the key-count check: without it,+ # concurrent new-key writes both observe space and overshoot the cap.+ Canvas.objects.for_team(self.team_id).select_for_update().get(pk=canvas.pk)+ if not existing.exists():+ if scoped.count() >= CANVAS_STATE_MAX_KEYS_PER_SCOPE:+ return Response(+ {+ "detail": f"A canvas may hold at most {CANVAS_STATE_MAX_KEYS_PER_SCOPE} state keys "+ "per scope. Delete keys (set them to null) or consolidate values."+ },+ status=status.HTTP_400_BAD_REQUEST,+ )+ entry, _ = CanvasState.objects.for_team(self.team_id).update_or_create(+ team_id=self.team_id, canvas=canvas, scope=scope, user=owner, key=key, defaults={"value": value}+ )+ return Response(CanvasStateEntrySerializer(entry).data)+def _log_canvas_activity(self, canvas: Canvas, activity: str, detail: Detail) -> None:log_activity(organization_id=self.team.organization_id,diff --git a/products/canvas/backend/source.py b/products/canvas/backend/source.pyindex bc98be28081a..d8520640e929 100644--- a/products/canvas/backend/source.py+++ b/products/canvas/backend/source.py@@ -14,6 +14,7 @@ import reimport jsonfrom typing import Any+from products.canvas.backend.actions import CANVAS_ACTIONSfrom products.canvas.backend.contract import (allowed_import_specifiers,canvas_sdk_version,@@ -80,6 +81,10 @@ _NETWORK_PATTERNS: list[tuple[re.Pattern[str], str, str]] = [_PH_LOAD_INSIGHT_RE = re.compile(r"\bph\s*\.\s*loadInsight\s*\(\s*(?:[\"']([^\"']+)[\"'])?")_PH_QUERY_RE = re.compile(r"\bph\s*\.\s*query\s*\(")_PH_CAPTURE_RE = re.compile(r"\bph\s*\.\s*capture\s*\(\s*(?:[\"']([^\"']+)[\"'])?")+_PH_STATE_RE = re.compile(r"\bph\s*\.\s*state\s*\.")+_PH_STATE_CALL_RE = re.compile(r"\bph\s*\.\s*state\s*\.\s*(get|set|list)\s*\(")+_STATE_SCOPE_LITERAL_RE = re.compile(r"\bscope\s*:\s*[\"']([^\"']+)[\"']")+_PH_ACTIONS_RE = re.compile(r"\bph\s*\.\s*actions\s*\.\s*invoke\s*\(\s*(?:[\"']([^\"']+)[\"'])?")_PATH_SEGMENT_RE = re.compile(r"^[A-Za-z0-9._@-]+$")@@ -209,6 +214,78 @@ def _validate_capabilities(path: str, code: str, capabilities: dict[str, Any]) -declared_events = set(posthog_capabilities.get("captureEvents") or [])inline_queries = bool(posthog_capabilities.get("inlineQueries"))+ declared_state = set(posthog_capabilities.get("state") or [])+ if not declared_state:+ state_match = _PH_STATE_RE.search(code)+ if state_match is not None:+ diagnostics.append(+ diagnostic(+ "error",+ "capability_missing_state",+ 'ph.state requires its scopes in capabilities.posthog.state (["user"] and/or ["shared"]) — '+ "the host rejects undeclared state access at runtime",+ path=path,+ line=_line_of(code, state_match.start()),+ )+ )+ else:+ # Declaring one scope is not declaring the other: check each call+ # site's scope — the explicit literal, or the runtime's "user"+ # default when get/set pass no options — against the declaration.+ for call in _PH_STATE_CALL_RE.finditer(code):+ window_end = min(len(code), call.end() + 200)+ next_call = _PH_STATE_CALL_RE.search(code, call.end())+ if next_call is not None:+ window_end = min(window_end, next_call.start())+ scope_literal = _STATE_SCOPE_LITERAL_RE.search(code, call.end(), window_end)+ used_scope = scope_literal.group(1) if scope_literal else None+ if used_scope is None:+ used_scope = "user" if call.group(1) in ("get", "set") else None+ if used_scope is not None and used_scope not in declared_state:+ line = _line_of(code, call.start())+ detail = (+ f'ph.state.{call.group(1)} uses scope "{used_scope}"'+ if scope_literal+ else f'ph.state.{call.group(1)} defaults to scope "user"'+ )+ diagnostics.append(+ diagnostic(+ "error",+ "capability_missing_state",+ f"{detail}, which capabilities.posthog.state does not declare — "+ "the host rejects undeclared state access at runtime",+ path=path,+ line=line,+ )+ )++ declared_action_verbs = set(posthog_capabilities.get("actions") or [])+ for match in _PH_ACTIONS_RE.finditer(code):+ verb = match.group(1)+ line = _line_of(code, match.start())+ if verb is not None and verb not in declared_action_verbs:+ diagnostics.append(+ diagnostic(+ "error",+ "capability_missing_action",+ f'ph.actions.invoke("{verb}") requires "{verb}" in capabilities.posthog.actions — '+ "the host rejects undeclared actions at runtime",+ path=path,+ line=line,+ )+ )+ elif verb is None and not declared_action_verbs:+ diagnostics.append(+ diagnostic(+ "warning",+ "capability_missing_action",+ "ph.actions.invoke() is called with a dynamic verb but capabilities.posthog.actions is empty — "+ "declare every verb the canvas invokes",+ path=path,+ line=line,+ )+ )+for match in _PH_LOAD_INSIGHT_RE.finditer(code):short_id = match.group(1)line = _line_of(code, match.start())@@ -311,6 +388,19 @@ def validate_source_project(project: dict[str, Any]) -> list[dict[str, Any]]:diagnostics.append(diagnostic("error", "network_origins_not_supported", "capabilities.network.origins must be empty"))+ declared_verbs = ((project.get("capabilities") or {}).get("posthog") or {}).get("actions") or []+ unregistered = sorted(set(declared_verbs) - set(CANVAS_ACTIONS))+ if unregistered:+ diagnostics.append(+ diagnostic(+ "error",+ "action_not_registered",+ "capabilities.posthog.actions declares unknown verbs: "+ + ", ".join(unregistered)+ + " — registered verbs: "+ + ", ".join(sorted(CANVAS_ACTIONS)),+ )+ )if len(files) + len(assets) > limits["maxSourceFiles"]:diagnostics.append(diagnostic(diff --git a/products/canvas/backend/tests/test_canvas_api.py b/products/canvas/backend/tests/test_canvas_api.pyindex 61dbd4e3372d..fefc4f1897d2 100644--- a/products/canvas/backend/tests/test_canvas_api.py+++ b/products/canvas/backend/tests/test_canvas_api.py@@ -5,6 +5,7 @@ from uuid import UUID, uuid4from posthog.test.base import APIBaseTestfrom unittest.mock import patch+from django.test import SimpleTestCasefrom django.utils import timezonefrom parameterized import parameterized@@ -19,7 +20,9 @@ from posthog.models.user import Userfrom posthog.models.utils import generate_random_token_personal, hash_key_valuefrom posthog.temporal.oauth import ARRAY_APP_CLIENT_ID_DEV+from products.annotations.backend.models.annotation import Annotationfrom products.canvas.backend import activity_visibility, build_service+from products.canvas.backend.actions import CANVAS_ACTIONS, TaskCreatePayloadSerializerfrom products.canvas.backend.models import Canvas, CanvasBuild, CanvasSourceVersionfrom products.canvas.backend.source import synthetic_source_projectfrom products.tasks.backend.logic.services.compute_quota import ComputeQuotaDenialReason@@ -888,11 +891,11 @@ class TestCanvasActivityLog(CanvasAPIBaseTest):assert first.status_code == status.HTTP_200_OK, first.json()default_capabilities = {- "posthog": {"insights": [], "inlineQueries": False, "captureEvents": []},+ "posthog": {"insights": [], "inlineQueries": False, "captureEvents": [], "state": [], "actions": []},"network": {"origins": []},}widened_capabilities = {- "posthog": {"insights": ["abc123"], "inlineQueries": True, "captureEvents": []},+ "posthog": {"insights": ["abc123"], "inlineQueries": True, "captureEvents": [], "state": [], "actions": []},"network": {"origins": []},}widened = self._project("export default function C() { return 2 }")@@ -1161,6 +1164,118 @@ class TestCanvasDraftBuilds(CanvasAPIBaseTest):assert builds["current_version_id"] == head_id+class TestCanvasState(CanvasAPIBaseTest):+ def _state_canvas(self, scopes: tuple[str, ...] = ("user", "shared")) -> str:+ canvas_id = self._create_canvas()+ capabilities = {+ "posthog": {"insights": [], "inlineQueries": False, "captureEvents": [], "state": list(scopes)},+ "network": {"origins": []},+ }+ response = self._publish(canvas_id, project=self._project(capabilities=capabilities))+ assert response.status_code == status.HTTP_200_OK, response.json()+ return canvas_id++ def _set_state(self, canvas_id: str, scope: str, key: str, value: Any):+ return self.client.post(+ f"/api/projects/{self.team.id}/canvases/{canvas_id}/state/set/",+ {"scope": scope, "key": key, "value": value},+ format="json",+ )++ def _entries(self, canvas_id: str) -> list[dict[str, Any]]:+ response = self.client.get(f"/api/projects/{self.team.id}/canvases/{canvas_id}/state/")+ assert response.status_code == status.HTTP_200_OK, response.json()+ return response.json()["entries"]++ def test_state_isolates_user_scope_and_shares_shared_scope(self):+ canvas_id = self._state_canvas()+ assert self._set_state(canvas_id, "shared", "board", {"columns": 3}).status_code == status.HTTP_200_OK+ assert self._set_state(canvas_id, "user", "draft", "mine").status_code == status.HTTP_200_OK++ teammate = self._create_user("[email protected]")+ self.client.force_login(teammate)+ assert self._set_state(canvas_id, "user", "draft", "theirs").status_code == status.HTTP_200_OK+ teammate_view = {(e["scope"], e["key"]): e["value"] for e in self._entries(canvas_id)}+ assert teammate_view == {("shared", "board"): {"columns": 3}, ("user", "draft"): "theirs"}++ self.client.force_login(self.user)+ own_view = {(e["scope"], e["key"]): e["value"] for e in self._entries(canvas_id)}+ assert own_view == {("shared", "board"): {"columns": 3}, ("user", "draft"): "mine"}++ def test_state_reads_only_declared_scopes(self):+ canvas_id = self._state_canvas()+ assert self._set_state(canvas_id, "shared", "board", 1).status_code == status.HTTP_200_OK+ assert self._set_state(canvas_id, "user", "draft", 2).status_code == status.HTTP_200_OK++ # Narrowing the declaration on a later publish must also stop reads of+ # entries written under the previously declared scope.+ narrowed = {+ "posthog": {"insights": [], "inlineQueries": False, "captureEvents": [], "state": ["shared"]},+ "network": {"origins": []},+ }+ assert self._publish(canvas_id, project=self._project(capabilities=narrowed)).status_code == status.HTTP_200_OK++ assert [(e["scope"], e["key"]) for e in self._entries(canvas_id)] == [("shared", "board")]++ def test_set_state_requires_the_scope_to_be_declared(self):+ canvas_id = self._state_canvas(scopes=("user",))++ denied = self._set_state(canvas_id, "shared", "k", 1)++ assert denied.status_code == status.HTTP_403_FORBIDDEN+ assert "shared" in denied.json()["detail"]+ assert self._set_state(canvas_id, "user", "k", 1).status_code == status.HTTP_200_OK++ def test_null_value_deletes_the_key(self):+ canvas_id = self._state_canvas()+ self._set_state(canvas_id, "shared", "flag", True)++ response = self._set_state(canvas_id, "shared", "flag", None)++ assert response.status_code == status.HTTP_204_NO_CONTENT+ assert self._entries(canvas_id) == []++ def test_state_write_bounds_are_enforced(self):+ canvas_id = self._state_canvas()++ oversized = self._set_state(canvas_id, "shared", "big", "x" * (64 * 1024))+ assert oversized.status_code == status.HTTP_400_BAD_REQUEST++ with patch("products.canvas.backend.presentation.views.CANVAS_STATE_MAX_KEYS_PER_SCOPE", 2):+ assert self._set_state(canvas_id, "shared", "one", 1).status_code == status.HTTP_200_OK+ assert self._set_state(canvas_id, "shared", "two", 2).status_code == status.HTTP_200_OK+ # Rewriting an existing key is not a new key, so it stays allowed.+ assert self._set_state(canvas_id, "shared", "one", 11).status_code == status.HTTP_200_OK+ assert self._set_state(canvas_id, "shared", "three", 3).status_code == status.HTTP_400_BAD_REQUEST++ def test_sandbox_tokens_cannot_use_state(self):+ canvas_id = self._state_canvas()+ task = Task.objects.create(+ team=self.team,+ channel=self.channel,+ created_by=self.user,+ title="State",+ description="d",+ origin_product=Task.OriginProduct.USER_CREATED,+ )+ Canvas.objects.unscoped().filter(id=canvas_id).update(generation_task_id=task.id)+ client = self._sandbox_client(task.id)++ read = client.get(+ f"/api/projects/{self.team.id}/canvases/{canvas_id}/state/",+ HTTP_X_POSTHOG_TASK_ID=str(task.id),+ )+ write = client.post(+ f"/api/projects/{self.team.id}/canvases/{canvas_id}/state/set/",+ {"scope": "shared", "key": "k", "value": 1},+ format="json",+ HTTP_X_POSTHOG_TASK_ID=str(task.id),+ )++ assert read.status_code == status.HTTP_403_FORBIDDEN+ assert write.status_code == status.HTTP_403_FORBIDDEN++class TestCanvasErrorReports(CanvasAPIBaseTest):def setUp(self):super().setUp()@@ -1387,3 +1502,138 @@ class TestCanvasErrorReports(CanvasAPIBaseTest):assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS, response.json()assert expected_detail in response.json()["detail"].lower()assert not TaskRun.objects.exists()+++class TestCanvasActions(CanvasAPIBaseTest):+ def _actions_canvas(self, verbs: tuple[str, ...] = ("tasks.create", "annotations.create")) -> str:+ canvas_id = self._create_canvas()+ capabilities = {+ "posthog": {+ "insights": [],+ "inlineQueries": False,+ "captureEvents": [],+ "state": [],+ "actions": list(verbs),+ },+ "network": {"origins": []},+ }+ response = self._publish(canvas_id, project=self._project(capabilities=capabilities))+ assert response.status_code == status.HTTP_200_OK, response.json()+ return canvas_id++ def _invoke(self, canvas_id: str, verb: str, payload: dict[str, Any]):+ return self.client.post(+ f"/api/projects/{self.team.id}/canvases/{canvas_id}/actions/invoke/",+ {"verb": verb, "payload": payload},+ format="json",+ )++ @parameterized.expand(+ [+ # canvas:write alone is not consent to write other resources.+ ("canvas_scope_only", ["canvas:write"], status.HTTP_403_FORBIDDEN),+ ("target_scope_held", ["canvas:write", "task:write"], status.HTTP_200_OK),+ ]+ )+ def test_scoped_keys_need_the_verbs_target_scope(self, _name, scopes, expected_status):+ canvas_id = self._actions_canvas()+ raw_key = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ label="canvas-actions", user=self.user, secure_value=hash_key_value(raw_key), scopes=scopes+ )+ self.client.logout()++ response = self.client.post(+ f"/api/projects/{self.team.id}/canvases/{canvas_id}/actions/invoke/",+ {"verb": "tasks.create", "payload": {"title": "Scoped", "description": ""}},+ format="json",+ HTTP_AUTHORIZATION=f"Bearer {raw_key}",+ )++ assert response.status_code == expected_status, response.json()++ def test_registry_lists_every_verb_with_authoring_docs(self):+ # Agents build against this endpoint instead of a skill file, so a verb+ # missing its usage docs means they guess payloads and confirmation copy.+ response = self.client.get(f"/api/projects/{self.team.id}/canvases/actions/")++ assert response.status_code == status.HTTP_200_OK, response.json()+ rows = {row["verb"]: row for row in response.json()["actions"]}+ assert set(rows) == set(CANVAS_ACTIONS)+ for row in rows.values():+ assert row["usage"].strip(), f"verb {row['verb']} shipped without usage docs"++ def test_tasks_create_files_a_task_in_the_canvas_channel_as_the_viewer(self):+ canvas_id = self._actions_canvas()++ response = self._invoke(canvas_id, "tasks.create", {"title": "Follow up", "description": "From the board"})++ assert response.status_code == status.HTTP_200_OK, response.json()+ task = Task.objects.get(id=response.json()["result"]["task_id"])+ assert task.created_by_id == self.user.id+ assert task.channel_id == self.channel.id+ assert task.title == "Follow up"++ def test_annotations_create_attributes_the_viewer(self):+ canvas_id = self._actions_canvas()++ response = self._invoke(canvas_id, "annotations.create", {"content": "Marked from the canvas"})++ assert response.status_code == status.HTTP_200_OK, response.json()+ annotation = Annotation.objects.get(id=response.json()["result"]["annotation_id"])+ assert annotation.created_by_id == self.user.id+ assert annotation.scope == Annotation.Scope.PROJECT+ assert annotation.content == "Marked from the canvas"+ # An omitted date_marker must resolve to a timestamp; a null marker+ # would leave the annotation off every chart and out of AI context.+ assert annotation.date_marker is not None++ def test_undeclared_and_unknown_verbs_are_refused(self):+ canvas_id = self._actions_canvas(verbs=("tasks.create",))++ undeclared = self._invoke(canvas_id, "annotations.create", {"content": "x"})+ unknown = self._invoke(canvas_id, "flags.delete", {})++ assert undeclared.status_code == status.HTTP_403_FORBIDDEN+ assert unknown.status_code == status.HTTP_400_BAD_REQUEST+ assert Annotation.objects.count() == 0++ def test_kill_switch_refuses_every_verb(self):+ canvas_id = self._actions_canvas()++ with patch("products.canvas.backend.presentation.views.canvas_actions_disabled", return_value=True):+ response = self._invoke(canvas_id, "tasks.create", {"title": "t"})++ assert response.status_code == status.HTTP_403_FORBIDDEN++ def test_sandbox_tokens_cannot_invoke_actions(self):+ canvas_id = self._actions_canvas()+ task = Task.objects.create(+ team=self.team,+ channel=self.channel,+ created_by=self.user,+ title="Actions",+ description="d",+ origin_product=Task.OriginProduct.USER_CREATED,+ )+ Canvas.objects.unscoped().filter(id=canvas_id).update(generation_task_id=task.id)+ client = self._sandbox_client(task.id)++ response = client.post(+ f"/api/projects/{self.team.id}/canvases/{canvas_id}/actions/invoke/",+ {"verb": "tasks.create", "payload": {"title": "t"}},+ format="json",+ HTTP_X_POSTHOG_TASK_ID=str(task.id),+ )++ assert response.status_code == status.HTTP_403_FORBIDDEN+++class TestTaskCreatePayloadSerializer(SimpleTestCase):+ def test_title_over_the_task_store_limit_is_rejected(self):+ # The task store caps title at 255; a longer value would reach Postgres+ # and 500 rather than surface as a field error, so the cap belongs here.+ serializer = TaskCreatePayloadSerializer(data={"title": "x" * 256, "description": ""})++ assert not serializer.is_valid()+ assert serializer.errors["title"][0].code == "max_length"diff --git a/products/canvas/backend/tests/test_capabilities.py b/products/canvas/backend/tests/test_capabilities.pyindex 5123a33284ec..54962ab5c739 100644--- a/products/canvas/backend/tests/test_capabilities.py+++ b/products/canvas/backend/tests/test_capabilities.py@@ -9,7 +9,13 @@ BASE = {"network": {"origins": []},}WIDER = {- "posthog": {"insights": ["abc", "def"], "captureEvents": ["clicked"], "inlineQueries": True},+ "posthog": {+ "insights": ["abc", "def"],+ "captureEvents": ["clicked"],+ "inlineQueries": True,+ "state": ["user"],+ "actions": ["tasks.create"],+ },"network": {"origins": ["https://api.example.com"]},}NARROWER = {@@ -37,6 +43,8 @@ class TestCapabilityWidening(TestCase):assert widening.capture_events_added == []assert widening.inline_queries_enabled is Trueassert widening.network_origins_added == ["https://api.example.com"]+ assert widening.state_scopes_added == ["user"]+ assert widening.actions_added == ["tasks.create"]def test_inline_queries_already_enabled_is_not_a_widening(self):enabled = {"posthog": {"inlineQueries": True}}diff --git a/products/canvas/backend/tests/test_cloud_builder.py b/products/canvas/backend/tests/test_cloud_builder.pyindex 306d4089e47f..7a21f672203b 100644--- a/products/canvas/backend/tests/test_cloud_builder.py+++ b/products/canvas/backend/tests/test_cloud_builder.py@@ -151,6 +151,44 @@ class TestCanvasCloudBuilder(SimpleTestCase):self.assertEqual(process.returncode, 0, process.stderr or process.stdout)+ def test_runtime_rejects_pre_connect_action_invocations(self) -> None:+ # Reads queue until the port connects, but a write queued during module+ # initialization would fire on connect as the viewer — an on-open task+ # or annotation the viewer never asked for. Writes must reject instead.+ result = run_cloud_builder(self._project('document.body.textContent = "Hello"'))++ runtime = next(file["content"] for file in result["files"] if file["path"] == "assets/canvas-runtime.js")+ harness = "\n".join(+ [+ "const listeners = {};",+ "const timers = new Map();",+ "let timerId = 0;",+ "globalThis.window = globalThis;",+ "globalThis.parent = {};",+ 'globalThis.document = { readyState: "complete", body: {}, head: { appendChild: () => {} }, addEventListener: () => {}, createElement: () => ({}) };',+ 'globalThis.location = { hash: "" };',+ "globalThis.MutationObserver = class { observe() {} };",+ "globalThis.addEventListener = (type, fn) => { (listeners[type] ||= []).push(fn); };",+ "globalThis.setTimeout = (fn) => { timers.set(++timerId, fn); return timerId; };",+ "globalThis.clearTimeout = (id) => { timers.delete(id); };",+ runtime,+ "const received = [];",+ "const port = { postMessage: (m) => received.push(m), addEventListener: () => {}, start: () => {} };",+ "let rejected = false;",+ 'window.ph.actions.invoke("tasks.create", { title: "on-open" }).catch(() => { rejected = true; });',+ 'for (const fn of listeners.message) fn({ source: parent, data: { channel: "posthog-canvas", type: "connect" }, ports: [port] });',+ "setImmediate(() => {",+ 'if (!rejected) { console.error("pre-connect action was not rejected"); process.exit(1); }',+ 'if (received.some((m) => m.type === "data-request" && m.method === "actionInvoke")) { console.error("pre-connect action was delivered on connect"); process.exit(1); }',+ "process.exit(0);",+ "});",+ ]+ )++ process = subprocess.run([node_executable()], input=harness, capture_output=True, text=True, timeout=60)++ self.assertEqual(process.returncode, 0, process.stderr or process.stdout)+def test_runtime_bounds_host_side_effects(self) -> None:result = run_cloud_builder(self._project('document.body.textContent = "Hello"'))diff --git a/products/canvas/backend/tests/test_source.py b/products/canvas/backend/tests/test_source.pyindex 91c88f754d28..74967b42a42a 100644--- a/products/canvas/backend/tests/test_source.py+++ b/products/canvas/backend/tests/test_source.py@@ -78,6 +78,39 @@ class TestCanvasSourceAdapter(SimpleTestCase):project(files={CANVAS_COMPONENT_PATH: 'import _ from "lodash";\n' + CODE}),"import_not_allowed",),+ (+ "undeclared_state_access",+ project(files={CANVAS_COMPONENT_PATH: CODE + 'ph.state.set("k", 1);'}),+ "capability_missing_state",+ ),+ (+ # get/set default to the user scope, so declaring only shared+ # does not cover a scopeless call.+ "state_default_user_scope_undeclared",+ project(+ files={CANVAS_COMPONENT_PATH: CODE + 'ph.state.set("k", 1);'},+ capabilities={"posthog": {"state": ["shared"]}, "network": {"origins": []}},+ ),+ "capability_missing_state",+ ),+ (+ "state_scope_literal_undeclared",+ project(+ files={CANVAS_COMPONENT_PATH: CODE + 'ph.state.get("k", { scope: "shared" });'},+ capabilities={"posthog": {"state": ["user"]}, "network": {"origins": []}},+ ),+ "capability_missing_state",+ ),+ (+ "undeclared_action_invoke",+ project(files={CANVAS_COMPONENT_PATH: CODE + 'ph.actions.invoke("tasks.create", {});'}),+ "capability_missing_action",+ ),+ (+ "unregistered_declared_action",+ project(capabilities={"posthog": {"actions": ["flags.delete"]}, "network": {"origins": []}}),+ "action_not_registered",+ ),("dynamic_import",project(files={CANVAS_COMPONENT_PATH: 'const m = await import("https://evil.dev/x.js");'}),@@ -129,6 +162,26 @@ class TestCanvasSourceAdapter(SimpleTestCase):self.assertTrue(has_errors(diagnostics), diagnostics)self.assertIn(expected_code, [d["code"] for d in diagnostics])+ @parameterized.expand(+ [+ # A scopeless get/set defaults to the user scope.+ ("default_user_scope", 'ph.state.set("k", 1);', ["user"]),+ ("explicit_scope_literal", 'ph.state.get("k", { scope: "shared" });', ["shared"]),+ # A scopeless list reads whatever is declared, so any declaration covers it.+ ("scopeless_list", "ph.state.list();", ["shared"]),+ ]+ )+ def test_declared_state_scopes_silence_the_state_diagnostic(self, _name, snippet, scopes):+ candidate = project(+ files={CANVAS_COMPONENT_PATH: CODE + snippet},+ capabilities={+ "posthog": {"insights": [], "inlineQueries": False, "captureEvents": [], "state": scopes},+ "network": {"origins": []},+ },+ )+ diagnostics = validate_source_project(candidate)+ self.assertNotIn("capability_missing_state", [d["code"] for d in diagnostics])+def test_direct_network_calls_warn_but_stay_publishable(self):# fetch() is blocked by the sandbox CSP, not by publish — a comment or# string mentioning it must not brick a canvas, so it's a warning.diff --git a/products/canvas/frontend/generated/api.schemas.ts b/products/canvas/frontend/generated/api.schemas.tsindex a1d1b6075a42..55d8897942d9 100644--- a/products/canvas/frontend/generated/api.schemas.ts+++ b/products/canvas/frontend/generated/api.schemas.ts@@ -143,6 +143,39 @@ export interface PatchedCanvasUpdateApi {generation_task_id?: string | null}+/**+ * Verb-specific arguments, validated against the verb's payload schema.+ */+export type CanvasActionInvokeApiPayload = { [key: string]: unknown }++/**+ * Payload for invoking one action verb.+ */+export interface CanvasActionInvokeApi {+ /**+ * Registered verb to invoke, e.g. 'tasks.create'.+ * @maxLength 64+ */+ verb: string+ /** Verb-specific arguments, validated against the verb's payload schema. */+ payload?: CanvasActionInvokeApiPayload+}++/**+ * Verb-specific result, e.g. {'task_id': ...} for tasks.create.+ */+export type CanvasActionResultApiResult = { [key: string]: unknown }++/**+ * Result of one action invocation.+ */+export interface CanvasActionResultApi {+ /** The verb that executed. */+ verb: string+ /** Verb-specific result, e.g. {'task_id': ...} for tasks.create. */+ result: CanvasActionResultApiResult+}+/*** * `queued` - queued* * `building` - building@@ -359,6 +392,17 @@ export interface CanvasSourceAssetApi {content: string}+/**+ * * `user` - user+ * * `shared` - shared+ */+export type CanvasStateScopeEnumApi = (typeof CanvasStateScopeEnumApi)[keyof typeof CanvasStateScopeEnumApi]++export const CanvasStateScopeEnumApi = {+ User: 'user',+ Shared: 'shared',+} as const+export interface CanvasPostHogCapabilitiesApi {/*** @maxItems 100@@ -371,6 +415,17 @@ export interface CanvasPostHogCapabilitiesApi {* @items.maxLength 200*/captureEvents: string[]+ /**+ * State scopes the canvas may use via ph.state: 'user' (private to each viewer) and/or 'shared' (one value per canvas, team-visible).+ * @maxItems 2+ */+ state?: CanvasStateScopeEnumApi[]+ /**+ * Registered action verbs the canvas may invoke via ph.actions (e.g. 'annotations.create', 'tasks.create'). Each executes as the viewer; declaring one shows it in the promote review.+ * @maxItems 32+ * @items.maxLength 64+ */+ actions?: string[]}export interface CanvasNetworkCapabilitiesApi {@@ -446,6 +501,10 @@ export interface CanvasCapabilityWideningApi {inline_queries_enabled: boolean/** Network origins the draft newly declares it may reach. */network_origins_added: string[]+ /** State scopes (user, shared) the draft newly declares for ph.state. */+ state_scopes_added: string[]+ /** Action verbs the draft newly declares it may invoke via ph.actions. */+ actions_added: string[]}/**@@ -746,6 +805,52 @@ export interface CanvasSourceResponseApi {current_version_id: string | null}+/**+ * One key of a canvas's runtime key-value state (the ph.state store).+ */+export interface CanvasStateEntryApi {+ /** user: private to the viewer who wrote it. shared: one value per canvas, visible to every viewer.+ *+ * * `user` - user+ * * `shared` - shared */+ scope: CanvasStateScopeEnumApi+ /**+ * The entry's key, unique within its scope.+ * @maxLength 200+ */+ key: string+ /** The stored JSON value. */+ value: unknown+ /** When the entry was last written. */+ updated_at: string+}++/**+ * The canvas state readable by the caller.+ */+export interface CanvasStateResponseApi {+ /** The canvas's shared entries plus the caller's own user-scoped entries. */+ entries: CanvasStateEntryApi[]+}++/**+ * Payload for writing (or deleting) one key of a canvas's runtime state.+ */+export interface CanvasStateSetApi {+ /** Scope to write into; the canvas must declare it in capabilities.posthog.state.+ *+ * * `user` - user+ * * `shared` - shared */+ scope: CanvasStateScopeEnumApi+ /**+ * Key to write, unique within its scope.+ * @maxLength 200+ */+ key: string+ /** JSON value to store (at most 64 KB serialized), or null to delete the key. */+ value: unknown+}+/*** Payload for validating a candidate source project without publishing it.*/@@ -802,6 +907,28 @@ export interface PaginatedCanvasVersionListApi {results: CanvasVersionApi[]}+/**+ * One registered action verb, as the host renders it before invoking.+ */+export interface CanvasActionDefinitionApi {+ /** The verb's registry name, e.g. 'annotations.create'. */+ verb: string+ /** One line naming what invoking the verb does. */+ summary: string+ /** True when the verb deletes or disables something; the host must confirm with the viewer first. */+ destructive: boolean+ /** Authoring docs for the verb: payload and result shape, behavior, and the confirmation copy it warrants. */+ usage: string+}++/**+ * The action registry: every verb a canvas may declare and invoke.+ */+export interface CanvasActionsResponseApi {+ /** Registered verbs, sorted by name. */+ actions: CanvasActionDefinitionApi[]+}+export type CanvasesListParams = {/*** Only return canvases in this channel.@@ -842,6 +969,20 @@ export type CanvasesSourceRetrieveParams = {version_id?: string}+export type CanvasesStateRetrieveParams = {+ /**+ * Only return entries in this scope.+ */+ scope?: CanvasesStateRetrieveScope+}++export type CanvasesStateRetrieveScope = (typeof CanvasesStateRetrieveScope)[keyof typeof CanvasesStateRetrieveScope]++export const CanvasesStateRetrieveScope = {+ Shared: 'shared',+ User: 'user',+} as const+export type CanvasesVersionsRetrieveParams = {/*** Number of results to return per page.diff --git a/products/canvas/frontend/generated/api.ts b/products/canvas/frontend/generated/api.tsindex 863abc15f96d..39f10fa30412 100644--- a/products/canvas/frontend/generated/api.ts+++ b/products/canvas/frontend/generated/api.ts@@ -9,6 +9,9 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'* OpenAPI spec version: 1.0.0*/import type {+ CanvasActionInvokeApi,+ CanvasActionResultApi,+ CanvasActionsResponseApi,CanvasApi,CanvasBuildActionApi,CanvasBuildApi,@@ -27,12 +30,16 @@ import type {CanvasSourcePublishApi,CanvasSourcePublishResponseApi,CanvasSourceResponseApi,+ CanvasStateEntryApi,+ CanvasStateResponseApi,+ CanvasStateSetApi,CanvasValidateRequestApi,CanvasValidateResponseApi,CanvasesBuildsRetrieveParams,CanvasesDraftsRetrieveParams,CanvasesListParams,CanvasesSourceRetrieveParams,+ CanvasesStateRetrieveParams,CanvasesVersionsRetrieveParams,PaginatedCanvasDraftListApi,PaginatedCanvasListApi,@@ -148,6 +155,31 @@ export const canvasesDestroy = async (projectId: string, id: string, options?: R})}+export const getCanvasesActionsInvokeUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/canvases/${id}/actions/invoke/`+}++/**+ * Invoke one registered action verb as the viewer.+ *+ * The canvas must declare the verb in capabilities.posthog.actions (the+ * reviewed permission boundary); the write itself runs with the viewer's+ * own permissions, exactly as if they acted in the app.+ */+export const canvasesActionsInvoke = async (+ projectId: string,+ id: string,+ canvasActionInvokeApi: CanvasActionInvokeApi,+ options?: RequestInit+): Promise<CanvasActionResultApi> => {+ return apiMutator<CanvasActionResultApi>(getCanvasesActionsInvokeUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(canvasActionInvokeApi),+ })+}+export const getCanvasesBuildsRetrieveUrl = (projectId: string, id: string, params?: CanvasesBuildsRetrieveParams) => {const normalizedParams = new URLSearchParams()@@ -474,6 +506,61 @@ export const canvasesSourceRetrieve = async (})}+export const getCanvasesStateRetrieveUrl = (projectId: string, id: string, params?: CanvasesStateRetrieveParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/canvases/${id}/state/?${stringifiedParams}`+ : `/api/projects/${projectId}/canvases/${id}/state/`+}++/**+ * Read the canvas's runtime key-value state (the ph.state store).+ *+ * Returns the canvas's shared entries plus the caller's own user-scoped+ * entries — never another viewer's.+ */+export const canvasesStateRetrieve = async (+ projectId: string,+ id: string,+ params?: CanvasesStateRetrieveParams,+ options?: RequestInit+): Promise<CanvasStateResponseApi> => {+ return apiMutator<CanvasStateResponseApi>(getCanvasesStateRetrieveUrl(projectId, id, params), {+ ...options,+ method: 'GET',+ })+}++export const getCanvasesStateSetUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/canvases/${id}/state/set/`+}++/**+ * Write one key of the canvas's runtime state, or delete it with a null value.+ */+export const canvasesStateSet = async (+ projectId: string,+ id: string,+ canvasStateSetApi: CanvasStateSetApi,+ options?: RequestInit+): Promise<CanvasStateEntryApi | void> => {+ return apiMutator<CanvasStateEntryApi | void>(getCanvasesStateSetUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(canvasStateSetApi),+ })+}+export const getCanvasesValidateCreateUrl = (projectId: string, id: string) => {return `/api/projects/${projectId}/canvases/${id}/validate/`}@@ -533,3 +620,20 @@ export const canvasesVersionsRetrieve = async (method: 'GET',})}++export const getCanvasesActionsRetrieveUrl = (projectId: string) => {+ return `/api/projects/${projectId}/canvases/actions/`+}++/**+ * List the action registry: every verb a canvas may declare and invoke.+ */+export const canvasesActionsRetrieve = async (+ projectId: string,+ options?: RequestInit+): Promise<CanvasActionsResponseApi> => {+ return apiMutator<CanvasActionsResponseApi>(getCanvasesActionsRetrieveUrl(projectId), {+ ...options,+ method: 'GET',+ })+}diff --git a/products/canvas/frontend/generated/api.zod.ts b/products/canvas/frontend/generated/api.zod.tsindex cc067f42894a..39d71b181500 100644--- a/products/canvas/frontend/generated/api.zod.ts+++ b/products/canvas/frontend/generated/api.zod.ts@@ -46,6 +46,28 @@ export const CanvasesPartialUpdateBody = /* @__PURE__ */ zod}).describe('Writable canvas fields: metadata only — source changes go through publish\/edit.')+/**+ * Invoke one registered action verb as the viewer.+ *+ * The canvas must declare the verb in capabilities.posthog.actions (the+ * reviewed permission boundary); the write itself runs with the viewer's+ * own permissions, exactly as if they acted in the app.+ */+export const canvasesActionsInvokeBodyVerbMax = 64++export const CanvasesActionsInvokeBody = /* @__PURE__ */ zod+ .object({+ verb: zod+ .string()+ .max(canvasesActionsInvokeBodyVerbMax)+ .describe("Registered verb to invoke, e.g. 'tasks.create'."),+ payload: zod+ .record(zod.string(), zod.unknown())+ .optional()+ .describe("Verb-specific arguments, validated against the verb's payload schema."),+ })+ .describe('Payload for invoking one action verb.')+/*** Apply a lifecycle action (retry, pin, unpin, cancel) to one build.*/@@ -79,6 +101,12 @@ export const canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogCaptureEventexport const canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogCaptureEventsMax = 100+export const canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogStateMax = 2++export const canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogActionsItemMax = 64++export const canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogActionsMax = 32+export const canvasesDraftCreateBodyProjectOneCapabilitiesOneNetworkOriginsItemMax = 2048export const canvasesDraftCreateBodyProjectOneCapabilitiesOneNetworkOriginsMax = 20@@ -150,6 +178,24 @@ export const CanvasesDraftCreateBody = /* @__PURE__ */ zod)).max(canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogCaptureEventsMax),+ state: zod+ .array(zod.enum(['user', 'shared']).describe('\* `user` - user\n\* `shared` - shared'))+ .max(canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogStateMax)+ .optional()+ .describe(+ "State scopes the canvas may use via ph.state: 'user' (private to each viewer) and\/or 'shared' (one value per canvas, team-visible)."+ ),+ actions: zod+ .array(+ zod+ .string()+ .max(canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogActionsItemMax)+ )+ .max(canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogActionsMax)+ .optional()+ .describe(+ "Registered action verbs the canvas may invoke via ph.actions (e.g. 'annotations.create', 'tasks.create'). Each executes as the viewer; declaring one shows it in the promote review."+ ),}),network: zod.object({origins: zod@@ -259,6 +305,12 @@ export const canvasesPublishCreateBodyProjectOneCapabilitiesOnePosthogCaptureEveexport const canvasesPublishCreateBodyProjectOneCapabilitiesOnePosthogCaptureEventsMax = 100+export const canvasesPublishCreateBodyProjectOneCapabilitiesOnePosthogStateMax = 2++export const canvasesPublishCreateBodyProjectOneCapabilitiesOnePosthogActionsItemMax = 64++export const canvasesPublishCreateBodyProjectOneCapabilitiesOnePosthogActionsMax = 32+export const canvasesPublishCreateBodyProjectOneCapabilitiesOneNetworkOriginsItemMax = 2048export const canvasesPublishCreateBodyProjectOneCapabilitiesOneNetworkOriginsMax = 20@@ -332,6 +384,24 @@ export const CanvasesPublishCreateBody = /* @__PURE__ */ zod)).max(canvasesPublishCreateBodyProjectOneCapabilitiesOnePosthogCaptureEventsMax),+ state: zod+ .array(zod.enum(['user', 'shared']).describe('\* `user` - user\n\* `shared` - shared'))+ .max(canvasesPublishCreateBodyProjectOneCapabilitiesOnePosthogStateMax)+ .optional()+ .describe(+ "State scopes the canvas may use via ph.state: 'user' (private to each viewer) and\/or 'shared' (one value per canvas, team-visible)."+ ),+ actions: zod+ .array(+ zod+ .string()+ .max(canvasesPublishCreateBodyProjectOneCapabilitiesOnePosthogActionsItemMax)+ )+ .max(canvasesPublishCreateBodyProjectOneCapabilitiesOnePosthogActionsMax)+ .optional()+ .describe(+ "Registered action verbs the canvas may invoke via ph.actions (e.g. 'annotations.create', 'tasks.create'). Each executes as the viewer; declaring one shows it in the promote review."+ ),}),network: zod.object({origins: zod@@ -437,6 +507,24 @@ export const CanvasesRevertCreateBody = /* @__PURE__ */ zod}).describe("Payload for reverting the canvas's head to an existing source version.")+/**+ * Write one key of the canvas's runtime state, or delete it with a null value.+ */+export const canvasesStateSetBodyKeyMax = 200++export const CanvasesStateSetBody = /* @__PURE__ */ zod+ .object({+ scope: zod+ .enum(['user', 'shared'])+ .describe('\* `user` - user\n\* `shared` - shared')+ .describe(+ 'Scope to write into; the canvas must declare it in capabilities.posthog.state.\n\n\* `user` - user\n\* `shared` - shared'+ ),+ key: zod.string().max(canvasesStateSetBodyKeyMax).describe('Key to write, unique within its scope.'),+ value: zod.unknown().describe('JSON value to store (at most 64 KB serialized), or null to delete the key.'),+ })+ .describe("Payload for writing (or deleting) one key of a canvas's runtime state.")+/*** Validate a candidate source project without publishing it. Side-effect free.*/@@ -453,6 +541,12 @@ export const canvasesValidateCreateBodyProjectOneCapabilitiesOnePosthogCaptureEvexport const canvasesValidateCreateBodyProjectOneCapabilitiesOnePosthogCaptureEventsMax = 100+export const canvasesValidateCreateBodyProjectOneCapabilitiesOnePosthogStateMax = 2++export const canvasesValidateCreateBodyProjectOneCapabilitiesOnePosthogActionsItemMax = 64++export const canvasesValidateCreateBodyProjectOneCapabilitiesOnePosthogActionsMax = 32+export const canvasesValidateCreateBodyProjectOneCapabilitiesOneNetworkOriginsItemMax = 2048export const canvasesValidateCreateBodyProjectOneCapabilitiesOneNetworkOriginsMax = 20@@ -524,6 +618,24 @@ export const CanvasesValidateCreateBody = /* @__PURE__ */ zod)).max(canvasesValidateCreateBodyProjectOneCapabilitiesOnePosthogCaptureEventsMax),+ state: zod+ .array(zod.enum(['user', 'shared']).describe('\* `user` - user\n\* `shared` - shared'))+ .max(canvasesValidateCreateBodyProjectOneCapabilitiesOnePosthogStateMax)+ .optional()+ .describe(+ "State scopes the canvas may use via ph.state: 'user' (private to each viewer) and\/or 'shared' (one value per canvas, team-visible)."+ ),+ actions: zod+ .array(+ zod+ .string()+ .max(canvasesValidateCreateBodyProjectOneCapabilitiesOnePosthogActionsItemMax)+ )+ .max(canvasesValidateCreateBodyProjectOneCapabilitiesOnePosthogActionsMax)+ .optional()+ .describe(+ "Registered action verbs the canvas may invoke via ph.actions (e.g. 'annotations.create', 'tasks.create'). Each executes as the viewer; declaring one shows it in the promote review."+ ),}),network: zod.object({origins: zoddiff --git a/products/canvas/mcp/tools.yaml b/products/canvas/mcp/tools.yamlindex 54d79eea68b5..cc1df1e8614d 100644--- a/products/canvas/mcp/tools.yaml+++ b/products/canvas/mcp/tools.yaml@@ -229,6 +229,12 @@ tools:param_overrides:id:description: ID of the canvas the project is for.+ canvases-actions-invoke:+ operation: canvases_actions_invoke+ enabled: false+ canvases-actions-retrieve:+ operation: canvases_actions_retrieve+ enabled: falsecanvases-build-action-create:operation: canvases_build_action_createenabled: false@@ -244,6 +250,12 @@ tools:canvases-revert-create:operation: canvases_revert_createenabled: false+ canvases-state-retrieve:+ operation: canvases_state_retrieve+ enabled: false+ canvases-state-set:+ operation: canvases_state_set+ enabled: falsecanvases-versions-retrieve:operation: canvases_versions_retrieveenabled: falsediff --git a/products/canvas/packages/canvas_builder/build.mjs b/products/canvas/packages/canvas_builder/build.mjsindex ea122a25c23d..8a8450d6a7dc 100644--- a/products/canvas/packages/canvas_builder/build.mjs+++ b/products/canvas/packages/canvas_builder/build.mjs@@ -27,7 +27,7 @@ const runtimePath = 'assets/canvas-runtime.js'// event, which fires after the app's module scripts have already run, so any// ph.* call issued during mount lands before the port exists. Those messages// queue (bounded, in case the host never connects) and flush on connect.-const runtime = `(()=>{const channel="posthog-canvas",pending=new Map,queued=[];let sequence=0,port;const post=(message)=>{const payload={channel,...message};if(port){port.postMessage(payload)}else if(queued.length<256){queued.push(payload)}};const call=(method,payload)=>new Promise((resolve,reject)=>{const id=String(++sequence);const timer=setTimeout(()=>{pending.delete(id);const queuedIndex=queued.findIndex((message)=>message.type==="data-request"&&message.id===id);if(queuedIndex>-1)queued.splice(queuedIndex,1);reject(new Error("Canvas request timed out"));},30000);pending.set(id,{resolve,reject,timer});post({type:"data-request",id,method,payload});});const applyTheme=(theme)=>{if(theme!=="dark"&&theme!=="light")return;const dark=theme==="dark";document.documentElement.classList.toggle("dark",dark);document.documentElement.style.colorScheme=dark?"dark":"light";};applyTheme(new URLSearchParams(location.hash.slice(1)).get("theme"));const receive=(event)=>{if(event.data?.channel!==channel)return;if(event.data.type==="set-theme"){applyTheme(event.data.theme);return}if(event.data.type!=="data-response")return;const request=pending.get(event.data.id);if(!request)return;pending.delete(event.data.id);clearTimeout(request.timer);event.data.ok?request.resolve(event.data.result):request.reject(new Error(event.data.error??"Canvas request failed"));};const capture=(event,properties,distinctId)=>{const normalized=properties??{};let serialized;try{serialized=JSON.stringify(normalized)}catch{throw new Error("Canvas capture properties must be serializable")};if(typeof serialized!=="string"||serialized.length>16384)throw new Error("Canvas capture properties are too large");return call("capture",{event,properties:normalized,distinctId})};const openExternal=(value)=>{const url=new URL(value);if(url.protocol!=="https:"||!(url.hostname==="posthog.com"||url.hostname.endsWith(".posthog.com")))throw new Error("Canvas external URL is not allowed");post({type:"open-external",url:url.href})};window.ph={loadInsight:(shortId,options)=>call("loadInsight",{shortId,dateRange:options?.dateRange}),query:(query,params)=>call("query",typeof query==="string"?{hogql:query,params:params??{}}:{query,params:params??{}}),capture,openExternal};addEventListener("message",(event)=>{if(port||event.source!==parent||event.data?.channel!==channel||event.data?.type!=="connect"||!event.ports[0])return;port=event.ports[0];port.addEventListener("message",receive);port.start();while(queued.length)port.postMessage(queued.shift());if(document.readyState!=="loading")post({type:"ready"});if(document.readyState==="complete")post({type:"rendered"});});addEventListener("error",(event)=>post({type:"error",message:event.message||"Canvas runtime error",stack:event.error?.stack}));addEventListener("unhandledrejection",(event)=>post({type:"error",message:event.reason instanceof Error?event.reason.message:String(event.reason),stack:event.reason instanceof Error?event.reason.stack:undefined}));addEventListener("DOMContentLoaded",()=>post({type:"ready"}));addEventListener("load",()=>post({type:"rendered"}));})();`+const runtime = `(()=>{const channel="posthog-canvas",pending=new Map,queued=[];let sequence=0,port;const post=(message)=>{const payload={channel,...message};if(port){port.postMessage(payload)}else if(queued.length<256){queued.push(payload)}};const call=(method,payload)=>new Promise((resolve,reject)=>{if(!port&&(method==="actionInvoke"||method==="agentRequest")){reject(new Error("Canvas actions require a user action"));return}const id=String(++sequence);const timer=setTimeout(()=>{pending.delete(id);const queuedIndex=queued.findIndex((message)=>message.type==="data-request"&&message.id===id);if(queuedIndex>-1)queued.splice(queuedIndex,1);reject(new Error("Canvas request timed out"));},30000);pending.set(id,{resolve,reject,timer});post({type:"data-request",id,method,payload});});const applyTheme=(theme)=>{if(theme!=="dark"&&theme!=="light")return;const dark=theme==="dark";document.documentElement.classList.toggle("dark",dark);document.documentElement.style.colorScheme=dark?"dark":"light";};applyTheme(new URLSearchParams(location.hash.slice(1)).get("theme"));const receive=(event)=>{if(event.data?.channel!==channel)return;if(event.data.type==="set-theme"){applyTheme(event.data.theme);return}if(event.data.type!=="data-response")return;const request=pending.get(event.data.id);if(!request)return;pending.delete(event.data.id);clearTimeout(request.timer);event.data.ok?request.resolve(event.data.result):request.reject(new Error(event.data.error??"Canvas request failed"));};const capture=(event,properties,distinctId)=>{const normalized=properties??{};let serialized;try{serialized=JSON.stringify(normalized)}catch{throw new Error("Canvas capture properties must be serializable")};if(typeof serialized!=="string"||serialized.length>16384)throw new Error("Canvas capture properties are too large");return call("capture",{event,properties:normalized,distinctId})};const openExternal=(value)=>{const url=new URL(value);if(url.protocol!=="https:"||!(url.hostname==="posthog.com"||url.hostname.endsWith(".posthog.com")))throw new Error("Canvas external URL is not allowed");post({type:"open-external",url:url.href})};window.ph={loadInsight:(shortId,options)=>call("loadInsight",{shortId,dateRange:options?.dateRange}),query:(query,params)=>call("query",typeof query==="string"?{hogql:query,params:params??{}}:{query,params:params??{}}),capture,openExternal,state:{get:(key,opts)=>call("stateGet",{key,scope:opts?.scope||"user"}),set:(key,value,opts)=>call("stateSet",{key,value:value===undefined?null:value,scope:opts?.scope||"user"}),list:(opts)=>call("stateList",{scope:opts?.scope})},actions:{invoke:(verb,payload)=>call("actionInvoke",{verb,payload:payload??{}})}};addEventListener("message",(event)=>{if(port||event.source!==parent||event.data?.channel!==channel||event.data?.type!=="connect"||!event.ports[0])return;port=event.ports[0];port.addEventListener("message",receive);port.start();while(queued.length)port.postMessage(queued.shift());if(document.readyState!=="loading")post({type:"ready"});if(document.readyState==="complete")post({type:"rendered"});});addEventListener("error",(event)=>post({type:"error",message:event.message||"Canvas runtime error",stack:event.error?.stack}));addEventListener("unhandledrejection",(event)=>post({type:"error",message:event.reason instanceof Error?event.reason.message:String(event.reason),stack:event.reason instanceof Error?event.reason.stack:undefined}));addEventListener("DOMContentLoaded",()=>post({type:"ready"}));addEventListener("load",()=>post({type:"rendered"}));})();`// A published canvas runs the runtime baked into its artifact by this builder,// while an unpublished one runs the desktop's sandbox document — two copies of// the same selection behavior. The pair below is ported from the desktop's@@ -215,7 +215,7 @@ function installSelectionSettleGate(doc, callbacks) {}const selectionRuntime = `(()=>{const channel="posthog-canvas";let port,timer=0,published=false;const anchorRect=${commentActionAnchorRect.toString()};const settleGate=${installSelectionSettleGate.toString()};const post=message=>port?.postMessage({channel,...message}),clear=()=>{if(!published)return;published=false;post({type:"text-selection-cleared"})},clearNative=()=>{getSelection()?.removeAllRanges();clear()},report=()=>{clearTimeout(timer);timer=setTimeout(()=>{const selection=getSelection();if(!selection||selection.isCollapsed||selection.rangeCount===0){clear();return}const range=selection.getRangeAt(0);if(!document.body.contains(range.startContainer)||!document.body.contains(range.endContainer)){clear();return}const before=document.createRange();before.selectNodeContents(document.body);before.setEnd(range.startContainer,range.startOffset);const through=document.createRange();through.selectNodeContents(document.body);through.setEnd(range.endContainer,range.endOffset);const whole=document.createRange();whole.selectNodeContents(document.body);const text=whole.toString(),start=before.toString().length,end=through.toString().length,quote=text.slice(start,end);if(!quote.trim()||quote.length>10000){clear();return}const rect=anchorRect(range.getClientRects?range.getClientRects():[],range.getBoundingClientRect());published=true;post({type:"text-selection",selection:{quote,prefix:text.slice(Math.max(0,start-32),start),suffix:text.slice(end,end+32),start,end,rect:{top:rect.top,right:rect.right,bottom:rect.bottom,left:rect.left}}})},80)};addEventListener("message",event=>{if(port||event.source!==parent||event.data?.channel!==channel||event.data?.type!=="connect"||!event.ports[0])return;port=event.ports[0];port.addEventListener("message",event=>{if(event.data?.channel===channel&&event.data?.type==="clear-text-selection")clearNative()});port.start()});const abort=()=>{clearTimeout(timer);clear()};settleGate(document,{onGestureStart:abort,onSelectionSettled:report,onIdleSelectionChange:report,onGestureCancel:abort});document.addEventListener("scroll",abort,true)})();`-const highlightRuntime = `(()=>{const channel="posthog-canvas",style=document.createElement("style");style.textContent="::highlight(posthog-canvas-comment){background:rgba(250,204,21,.32);color:inherit}::highlight(posthog-canvas-comment-active){background:rgba(250,204,21,.48);color:inherit}";document.head.appendChild(style);let items=[],ranges=[],port,timer=0;const indexText=()=>{const walker=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT),entries=[];let text="";for(let node=walker.nextNode();node;node=walker.nextNode()){const start=text.length;text+=node.data;entries.push({node,start,end:text.length})}return{text,entries}},rangeAt=(index,start,end)=>{const find=offset=>{let low=0,high=index.entries.length-1,match=null;while(low<=high){const middle=low+high>>1,entry=index.entries[middle];if(offset<entry.start)high=middle-1;else if(offset>entry.end)low=middle+1;else{match=entry;high=middle-1}}return match},startEntry=find(start),endEntry=find(end);if(!startEntry||!endEntry)return null;const range=document.createRange();range.setStart(startEntry.node,start-startEntry.start);range.setEnd(endEntry.node,end-endEntry.start);return range},resolve=(text,anchor)=>{if(text.slice(anchor.start,anchor.end)===anchor.quote)return{start:anchor.start,end:anchor.end};const matches=[];for(let start=text.indexOf(anchor.quote);start>=0;start=text.indexOf(anchor.quote,start+Math.max(anchor.quote.length,1))){const end=start+anchor.quote.length,prefix=text.slice(Math.max(0,start-anchor.prefix.length),start),suffix=text.slice(end,end+anchor.suffix.length);matches.push({start,end,score:(anchor.prefix&&prefix===anchor.prefix?2:0)+(anchor.suffix&&suffix===anchor.suffix?2:0)})}if(matches.length===1)return matches[0];matches.sort((a,b)=>b.score-a.score);return matches[0]?.score&&matches[0].score!==matches[1]?.score?matches[0]:null},render=next=>{items=next||[];ranges=[];if(!window.Highlight||!window.CSS||!CSS.highlights)return;const normal=new Highlight,active=new Highlight,index=indexText();for(const item of items){const hit=resolve(index.text,item.anchor),range=hit&&rangeAt(index,hit.start,hit.end);if(range){ranges.push({id:item.id,range});(item.active?active:normal).add(range)}}CSS.highlights.set("posthog-canvas-comment",normal);CSS.highlights.set("posthog-canvas-comment-active",active)};addEventListener("message",event=>{if(port||event.source!==parent||event.data?.channel!==channel||event.data?.type!=="connect"||!event.ports[0])return;port=event.ports[0];port.addEventListener("message",event=>{if(event.data?.channel===channel&&event.data?.type==="set-comment-highlights")render(event.data.highlights)});port.start()});document.addEventListener("click",event=>{const selection=getSelection();if(selection&&!selection.isCollapsed)return;for(const item of ranges)for(const rect of item.range.getClientRects())if(event.clientX>=rect.left&&event.clientX<=rect.right&&event.clientY>=rect.top&&event.clientY<=rect.bottom){event.preventDefault();event.stopPropagation();port?.postMessage({channel,type:"comment-activate",id:item.id});return}},true);new MutationObserver(()=>{if(!items.length||timer)return;timer=setTimeout(()=>{timer=0;render(items)},500)}).observe(document.body,{childList:true,characterData:true,subtree:true})})();`+const highlightRuntime = `(()=>{const channel="posthog-canvas",style=document.createElement("style");style.textContent="::highlight(posthog-canvas-comment){background:rgba(250,204,21,.32);color:inherit}::highlight(posthog-canvas-comment-active){background:rgba(250,204,21,.48);color:inherit}";document.head.appendChild(style);let items=[],ranges=[],port,timer=0;const indexText=()=>{const walker=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT),entries=[];let text="";for(let node=walker.nextNode();node;node=walker.nextNode()){const start=text.length;text+=node.data;entries.push({node,start,end:text.length})}return{text,entries}},rangeAt=(index,start,end)=>{const find=offset=>{let low=0,high=index.entries.length-1,match=null;while(low<=high){const middle=low+high>>1,entry=index.entries[middle];if(offset<entry.start)high=middle-1;else if(offset>entry.end)low=middle+1;else{match=entry;high=middle-1}}return match},startEntry=find(start),endEntry=find(end);if(!startEntry||!endEntry)return null;const range=document.createRange();range.setStart(startEntry.node,start-startEntry.start);range.setEnd(endEntry.node,end-endEntry.start);return range},resolve=(text,anchor)=>{if(text.slice(anchor.start,anchor.end)===anchor.quote)return{start:anchor.start,end:anchor.end};const matches=[];for(let start=text.indexOf(anchor.quote);start>=0;start=text.indexOf(anchor.quote,start+Math.max(anchor.quote.length,1))){const end=start+anchor.quote.length,prefix=text.slice(Math.max(0,start-anchor.prefix.length),start),suffix=text.slice(end,end+anchor.suffix.length);matches.push({start,end,score:(anchor.prefix&&prefix===anchor.prefix?2:0)+(anchor.suffix&&suffix===anchor.suffix?2:0)})}if(matches.length===1)return matches[0];matches.sort((a,b)=>b.score-a.score);return matches[0]?.score&&matches[0].score!==matches[1]?.score?matches[0]:null},render=next=>{items=next||[];ranges=[];if(!window.Highlight||!window.CSS||!CSS.highlights)return;const normal=new Highlight,active=new Highlight,index=indexText();for(const item of items){const hit=resolve(index.text,item.anchor),range=hit&&rangeAt(index,hit.start,hit.end);if(range){ranges.push({id:item.id,range});(item.active?active:normal).add(range)}}CSS.highlights.set("posthog-canvas-comment",normal);CSS.highlights.set("posthog-canvas-comment-active",active)};addEventListener("message",event=>{if(port||event.source!==parent||event.data?.channel!==channel||event.data?.type!=="connect"||!event.ports[0])return;port=event.ports[0];port.addEventListener("message",event=>{if(event.data?.channel===channel&&event.data?.type==="set-comment-highlights")render(event.data.highlights)});port.start()});document.addEventListener("click",event=>{const selection=getSelection();if(selection&&!selection.isCollapsed)return;for(const item of ranges)for(const rect of item.range.getClientRects())if(event.clientX>=rect.left&&event.clientX<=rect.right&&event.clientY>=rect.top&&event.clientY<=rect.bottom){event.preventDefault();event.stopPropagation();port?.postMessage({channel,type:"comment-activate",id:item.id});return}},true);const observeBody=()=>new MutationObserver(()=>{if(!items.length||timer)return;timer=setTimeout(()=>{timer=0;render(items)},500)}).observe(document.body,{childList:true,characterData:true,subtree:true});document.body?observeBody():addEventListener("DOMContentLoaded",observeBody)})();`// Selection and highlight runtimes extend the shared canvas bridge.const platformStylesheet = `@import "tailwindcss";diff --git a/products/canvas/packages/canvas_builder/manifest.json b/products/canvas/packages/canvas_builder/manifest.jsonindex 2f2783c00851..03224ab5195f 100644--- a/products/canvas/packages/canvas_builder/manifest.json+++ b/products/canvas/packages/canvas_builder/manifest.json@@ -32,6 +32,8 @@"maxSourceTotalBytes": 2097152,"maxArtifactFiles": 256,"maxArtifactFileBytes": 4194304,- "maxArtifactTotalBytes": 12582912+ "maxArtifactTotalBytes": 12582912,+ "maxStateValueBytes": 65536,+ "maxStateKeysPerScope": 256}}diff --git a/products/canvas/skills/building-canvases/SKILL.md b/products/canvas/skills/building-canvases/SKILL.mdindex 80060a9bda8b..4c6052acb244 100644--- a/products/canvas/skills/building-canvases/SKILL.md+++ b/products/canvas/skills/building-canvases/SKILL.md@@ -106,6 +106,21 @@ canvas tools return (`canvas-create`, `canvas-list`, and the publish/source respThat field is the only valid link to a canvas — never construct one yourself; guessed URLs(project pages, web routes) do not resolve.+## Runtime memory and actions++- **`ph.state`** — durable key-value memory: `ph.state.get(key, { scope })`,+ `ph.state.set(key, value, { scope })` (a null value deletes the key), `ph.state.list({ scope })`.+ Scope `"user"` (the default) is private to each viewer; `"shared"` is one value per canvas,+ visible to the whole team. Declare the scopes you use in `capabilities.posthog.state`.+ Values are JSON, capped at 64 KB serialized and 256 keys per scope — store big data in+ PostHog (insights, the warehouse) and reference it. Never put secrets or viewer PII in state.+- **`ph.actions.invoke(verb, payload)`** — write into PostHog as the viewer. Declare every verb+ in `capabilities.posthog.actions`; undeclared or unregistered verbs fail validation and the+ host refuses them at runtime. Wire actions to explicit user gestures (a button the viewer+ clicks), never to load or render. The registry is the source of truth: list it with the+ `canvases-actions-retrieve` tool and follow each verb's `usage` (payload/result shape,+ behavior, and the confirmation copy it warrants) before wiring it.+## Source-project shape- Keep `index.html` as the entry shell returned by the source tool.diff --git a/products/canvas/skills/building-react-quill-canvases/SKILL.md b/products/canvas/skills/building-react-quill-canvases/SKILL.mdindex f788e7f60ea8..aeb7d37b3eec 100644--- a/products/canvas/skills/building-react-quill-canvases/SKILL.md+++ b/products/canvas/skills/building-react-quill-canvases/SKILL.md@@ -118,3 +118,12 @@ native date input) inside a `Popover` whose trigger is a Quill `Button`. `Popoveexactly `className="w-auto p-0"` and nothing is added to `DateTimePicker` beyond`value`/`onApply`/`onCancel` (it self-sizes; don't pass `compact` or widths). Re-run every querywhen the window changes — see the `querying-canvas-data` skill for feeding it into `dateRange`.++## State and actions++Persisting values across reloads (`ph.state`, with user/shared scopes) and writing into PostHog+from a button (`ph.actions.invoke`, e.g. filing a task or an annotation) have their own API+contracts, capability declarations, and gesture rules — read the "Runtime memory" and "PostHog+writes" sections of the `querying-canvas-data` skill before using either. Wire actions to a+`Button` `onClick` that disables itself while the call is in flight, and render the returned+error (they are real PostHog writes, throttled server-side).diff --git a/products/canvas/skills/querying-canvas-data/SKILL.md b/products/canvas/skills/querying-canvas-data/SKILL.mdindex 42d1333de0f7..d0a9169a33f4 100644--- a/products/canvas/skills/querying-canvas-data/SKILL.md+++ b/products/canvas/skills/querying-canvas-data/SKILL.md@@ -90,6 +90,48 @@ product — rather than every tile resolving the insight's saved default.- Values are typed by the variable's definition in PostHog (String / Number / Boolean / Date / List);pass the same shape the insight expects, and an array for a multi-select List variable.+## Runtime memory — ph.state++Durable key-value storage per canvas. Declare every scope you use in `capabilities.posthog.state`+(`["user"]`, `["shared"]`, or both) — undeclared scopes fail validation and the host refuses them+at runtime. Scope `"user"` (the default when no scope is passed) is private to each viewer;+`"shared"` is one value per canvas, visible to the whole team.++```tsx+const draft = await ph.state.get('draft') // user scope by default; null when unset+await ph.state.set('draft', { text }) // JSON value, capped at 64 KB serialized+await ph.state.set('draft', null) // null deletes the key+await ph.state.set('board', { columns }, { scope: 'shared' }) // team-visible+const entries = await ph.state.list({ scope: 'shared' }) // [{ scope, key, value, updatedAt }]+```++- Load state in an effect on mount and render a skeleton until it resolves; writes are+ last-write-wins, so re-read (or trust your own write) rather than merging.+- 256 keys per scope. Store big data in PostHog (insights, the warehouse) and reference it.+- State is team-visible application data — never secrets, never viewer PII.++## PostHog writes — ph.actions++`ph.actions.invoke(verb, payload)` writes into PostHog as the viewer. Declare every verb in+`capabilities.posthog.actions`; undeclared or unregistered verbs fail validation and the host+refuses them at runtime. Invocations must be wired to an explicit user gesture (a button the+viewer clicks) — the host rejects calls made on load or render.++Render the result or the thrown error visibly, and disable the button while the call is in+flight — every invocation is a real PostHog write.++The registry is the source of truth for verbs. Before wiring one, list it with the+`canvases-actions-retrieve` tool: each entry carries `verb`, `summary`, `destructive`, and+`usage` — the payload and result shape, what invoking it actually does, and the confirmation+copy it warrants. Follow a verb's `usage` exactly, including what the success message may claim.+Do not infer a verb's payload from the matching product's own MCP tools or skills — an MCP tool+call (you, now, with your credentials) and a canvas verb (the viewer, later, in the published+canvas) differ in payload shape, auth, and behavior. Invoking looks like:++```tsx+const { result } = await ph.actions.invoke('tasks.create', { title, description })+```+## Side effects- `ph.capture(event, properties?, distinctId?)` — analytics events for interactionsdiff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 2f46b3c4e090..8ea2c7af3145 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -176,6 +176,7 @@ __all__ = ["build_sandbox_custom_image","create_sandbox_custom_image","create_sandbox_environment",+ "create_channel_task","create_task","create_task_automation","create_task_without_run",@@ -1301,13 +1302,17 @@ def create_task_without_run(description: str = "",repository: str | None = None,mcp_builtin_agent_key: MCPBuiltInAgentKey | None = None,+ channel: Channel | None = None,) -> UUID:"""Create a Task row with no initial run, returning its id.For callers that own run creation themselves — e.g. the sandbox warm path, which boots the firstrun via the warming facade. ``team`` is a core ``posthog.Team`` (not a tasks model)."""- channel = None if origin_product in TEAM_READABLE_ORIGIN_PRODUCTS else _ensure_personal_channel(team.id, user_id)+ if channel is None:+ channel = (+ None if origin_product in TEAM_READABLE_ORIGIN_PRODUCTS else _ensure_personal_channel(team.id, user_id)+ )task = Task.create_without_run(team=team,title=title,@@ -1321,6 +1326,26 @@ def create_task_without_run(return task.id+def create_channel_task(team_id: int, user_id: int, channel_id: str | UUID, *, title: str, description: str) -> UUID:+ """Create a task filed into a channel, as the user — for product surfaces+ (canvas actions) that file work into their own channel. No initial run:+ the channel's feed shows it and the user drives it from there.+ """+ channel = (+ Channel.objects.for_team(team_id).filter(Channel.visible_to_q(user_id), id=channel_id, deleted=False).first()+ )+ if channel is None:+ raise ValueError("Channel not found in this team.")+ return create_task_without_run(+ team=Team.objects.get(id=team_id),+ user_id=user_id,+ origin_product=Task.OriginProduct.USER_CREATED,+ title=title,+ description=description,+ channel=channel,+ )++def create_run(task_id: str | UUID,*,diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.pyindex 28e5068d394e..64fb635da621 100644--- a/products/tasks/backend/tests/test_facade.py+++ b/products/tasks/backend/tests/test_facade.py@@ -783,6 +783,29 @@ class TestFacadeReadsAndMappers(TestCase):self.assertEqual(task.channel.channel_type, Channel.ChannelType.PERSONAL)self.assertEqual(task.channel.created_by_id, self.user.id)+ @parameterized.expand(+ [+ ("public", lambda self: self._make_channel().id, True),+ ("unknown", lambda _self: uuid4(), False),+ # Same rule as create_and_run_task above: someone else's "#me" is private,+ # so filing into it must be refused, not just team-filtered.+ ("other_users_personal", lambda self: self._make_teammates_personal_channel().id, False),+ ]+ )+ def test_create_channel_task_respects_channel_visibility(self, _name, make_channel_id, expect_filed):+ channel_id = make_channel_id(self)++ if expect_filed:+ task_id = facade.create_channel_task(+ self.team.id, self.user.id, channel_id, title="From canvas", description="desc"+ )+ self.assertEqual(Task.objects.get(id=task_id).channel_id, channel_id)+ else:+ with self.assertRaises(ValueError):+ facade.create_channel_task(+ self.team.id, self.user.id, channel_id, title="From canvas", description="desc"+ )+def test_ensure_personal_channel_id_idempotent_outside_request_scope(self):# No ambient team_scope here, like a Temporal activity — guards the for_team scoping.first = facade.ensure_personal_channel_id(self.team.id, self.user.id)diff --git a/pyproject.toml b/pyproject.tomlindex ebe1b6486e77..4659c757c7a5 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -546,7 +546,10 @@ ignore_imports = ["products.canvas.backend.presentation.serializers -> products.canvas.backend.artifacts","products.canvas.backend.presentation.serializers -> products.canvas.backend.contract","products.canvas.backend.presentation.serializers -> products.canvas.backend.models",+ "products.canvas.backend.presentation.views -> products.canvas.backend.actions","products.canvas.backend.presentation.views -> products.canvas.backend.build_service",+ "products.canvas.backend.presentation.views -> products.canvas.backend.capabilities",+ "products.canvas.backend.presentation.views -> products.canvas.backend.contract","products.canvas.backend.presentation.views -> products.canvas.backend.error_reports","products.canvas.backend.presentation.views -> products.canvas.backend.models","products.canvas.backend.presentation.views -> products.canvas.backend.source",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 45e4e5ab5011..a9917ae6e6d5 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -14336,6 +14336,61 @@ export namespace Schemas {readonly url: string;}+ /**+ * One registered action verb, as the host renders it before invoking.+ */+ export interface CanvasActionDefinition {+ /** The verb's registry name, e.g. 'annotations.create'. */+ verb: string;+ /** One line naming what invoking the verb does. */+ summary: string;+ /** True when the verb deletes or disables something; the host must confirm with the viewer first. */+ destructive: boolean;+ /** Authoring docs for the verb: payload and result shape, behavior, and the confirmation copy it warrants. */+ usage: string;+ }++ /**+ * Verb-specific arguments, validated against the verb's payload schema.+ */+ export type CanvasActionInvokePayload = { [key: string]: unknown };++ /**+ * Payload for invoking one action verb.+ */+ export interface CanvasActionInvoke {+ /**+ * Registered verb to invoke, e.g. 'tasks.create'.+ * @maxLength 64+ */+ verb: string;+ /** Verb-specific arguments, validated against the verb's payload schema. */+ payload?: CanvasActionInvokePayload;+ }++ /**+ * Verb-specific result, e.g. {'task_id': ...} for tasks.create.+ */+ export type CanvasActionResultResult = { [key: string]: unknown };++ /**+ * Result of one action invocation.+ */+ export interface CanvasActionResult {+ /** The verb that executed. */+ verb: string;+ /** Verb-specific result, e.g. {'task_id': ...} for tasks.create. */+ result: CanvasActionResultResult;+ }++ /**+ * The action registry: every verb a canvas may declare and invoke.+ */+ export interface CanvasActionsResponse {+ /** Registered verbs, sorted by name. */+ actions: CanvasActionDefinition[];+ }+/*** One emitted file of a built canvas artifact.*/@@ -14482,6 +14537,18 @@ export namespace Schemas {builds: CanvasBuild[];}+ /**+ * * `user` - user+ * * `shared` - shared+ */+ export type CanvasStateScopeEnum = typeof CanvasStateScopeEnum[keyof typeof CanvasStateScopeEnum];+++ export const CanvasStateScopeEnum = {+ User: 'user',+ Shared: 'shared',+ } as const;+export interface CanvasPostHogCapabilities {/*** @maxItems 100@@ -14494,6 +14561,17 @@ export namespace Schemas {* @items.maxLength 200*/captureEvents: string[];+ /**+ * State scopes the canvas may use via ph.state: 'user' (private to each viewer) and/or 'shared' (one value per canvas, team-visible).+ * @maxItems 2+ */+ state?: CanvasStateScopeEnum[];+ /**+ * Registered action verbs the canvas may invoke via ph.actions (e.g. 'annotations.create', 'tasks.create'). Each executes as the viewer; declaring one shows it in the promote review.+ * @maxItems 32+ * @items.maxLength 64+ */+ actions?: string[];}export interface CanvasNetworkCapabilities {@@ -14524,6 +14602,10 @@ export namespace Schemas {inline_queries_enabled: boolean;/** Network origins the draft newly declares it may reach. */network_origins_added: string[];+ /** State scopes (user, shared) the draft newly declares for ph.state. */+ state_scopes_added: string[];+ /** Action verbs the draft newly declares it may invoke via ph.actions. */+ actions_added: string[];}/**@@ -14926,6 +15008,52 @@ export namespace Schemas {current_version_id: string | null;}+ /**+ * One key of a canvas's runtime key-value state (the ph.state store).+ */+ export interface CanvasStateEntry {+ /** user: private to the viewer who wrote it. shared: one value per canvas, visible to every viewer.+ *+ * * `user` - user+ * * `shared` - shared */+ scope: CanvasStateScopeEnum;+ /**+ * The entry's key, unique within its scope.+ * @maxLength 200+ */+ key: string;+ /** The stored JSON value. */+ value: unknown;+ /** When the entry was last written. */+ updated_at: string;+ }++ /**+ * The canvas state readable by the caller.+ */+ export interface CanvasStateResponse {+ /** The canvas's shared entries plus the caller's own user-scoped entries. */+ entries: CanvasStateEntry[];+ }++ /**+ * Payload for writing (or deleting) one key of a canvas's runtime state.+ */+ export interface CanvasStateSet {+ /** Scope to write into; the canvas must declare it in capabilities.posthog.state.+ *+ * * `user` - user+ * * `shared` - shared */+ scope: CanvasStateScopeEnum;+ /**+ * Key to write, unique within its scope.+ * @maxLength 200+ */+ key: string;+ /** JSON value to store (at most 64 KB serialized), or null to delete the key. */+ value: unknown;+ }+/*** Payload for validating a candidate source project without publishing it.*/@@ -82927,6 +83055,21 @@ export namespace Schemas {version_id?: string;};+ export type CanvasesStateRetrieveParams = {+ /**+ * Only return entries in this scope.+ */+ scope?: CanvasesStateRetrieveScope;+ };++ export type CanvasesStateRetrieveScope = typeof CanvasesStateRetrieveScope[keyof typeof CanvasesStateRetrieveScope];+++ export const CanvasesStateRetrieveScope = {+ Shared: 'shared',+ User: 'user',+ } as const;+export type CanvasesVersionsRetrieveParams = {/*** Number of results to return per page.diff --git a/services/mcp/src/generated/canvas/api.ts b/services/mcp/src/generated/canvas/api.tsindex 538dc6154ddc..a5743e578d23 100644--- a/services/mcp/src/generated/canvas/api.ts+++ b/services/mcp/src/generated/canvas/api.ts@@ -111,6 +111,12 @@ export const canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogCaptureEventexport const canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogCaptureEventsMax = 100+export const canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogStateMax = 2++export const canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogActionsItemMax = 64++export const canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogActionsMax = 32+export const canvasesDraftCreateBodyProjectOneCapabilitiesOneNetworkOriginsItemMax = 2048export const canvasesDraftCreateBodyProjectOneCapabilitiesOneNetworkOriginsMax = 20@@ -182,6 +188,24 @@ export const CanvasesDraftCreateBody = /* @__PURE__ */ zod)).max(canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogCaptureEventsMax),+ state: zod+ .array(zod.enum(['user', 'shared']).describe('\* `user` - user\n\* `shared` - shared'))+ .max(canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogStateMax)+ .optional()+ .describe(+ "State scopes the canvas may use via ph.state: 'user' (private to each viewer) and\/or 'shared' (one value per canvas, team-visible)."+ ),+ actions: zod+ .array(+ zod+ .string()+ .max(canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogActionsItemMax)+ )+ .max(canvasesDraftCreateBodyProjectOneCapabilitiesOnePosthogActionsMax)+ .optional()+ .describe(+ "Registered action verbs the canvas may invoke via ph.actions (e.g. 'annotations.create', 'tasks.create'). Each executes as the viewer; declaring one shows it in the promote review."+ ),}),network: zod.object({origins: zod@@ -338,6 +362,12 @@ export const canvasesPublishCreateBodyProjectOneCapabilitiesOnePosthogCaptureEveexport const canvasesPublishCreateBodyProjectOneCapabilitiesOnePosthogCaptureEventsMax = 100+export const canvasesPublishCreateBodyProjectOneCapabilitiesOnePosthogStateMax = 2++export const canvasesPublishCreateBodyProjectOneCapabilitiesOnePosthogActionsItemMax = 64++export const canvasesPublishCreateBodyProjectOneCapabilitiesOnePosthogActionsMax = 32+export const canvasesPublishCreateBodyProjectOneCapabilitiesOneNetworkOriginsItemMax = 2048export const canvasesPublishCreateBodyProjectOneCapabilitiesOneNetworkOriginsMax = 20@@ -411,6 +441,24 @@ export const CanvasesPublishCreateBody = /* @__PURE__ */ zod)).max(canvasesPublishCreateBodyProjectOneCapabilitiesOnePosthogCaptureEventsMax),+ state: zod+ .array(zod.enum(['user', 'shared']).describe('\* `user` - user\n\* `shared` - shared'))+ .max(canvasesPublishCreateBodyProjectOneCapabilitiesOnePosthogStateMax)+ .optional()+ .describe(+ "State scopes the canvas may use via ph.state: 'user' (private to each viewer) and\/or 'shared' (one value per canvas, team-visible)."+ ),+ actions: zod+ .array(+ zod+ .string()+ .max(canvasesPublishCreateBodyProjectOneCapabilitiesOnePosthogActionsItemMax)+ )+ .max(canvasesPublishCreateBodyProjectOneCapabilitiesOnePosthogActionsMax)+ .optional()+ .describe(+ "Registered action verbs the canvas may invoke via ph.actions (e.g. 'annotations.create', 'tasks.create'). Each executes as the viewer; declaring one shows it in the promote review."+ ),}),network: zod.object({origins: zod@@ -514,6 +562,12 @@ export const canvasesValidateCreateBodyProjectOneCapabilitiesOnePosthogCaptureEvexport const canvasesValidateCreateBodyProjectOneCapabilitiesOnePosthogCaptureEventsMax = 100+export const canvasesValidateCreateBodyProjectOneCapabilitiesOnePosthogStateMax = 2++export const canvasesValidateCreateBodyProjectOneCapabilitiesOnePosthogActionsItemMax = 64++export const canvasesValidateCreateBodyProjectOneCapabilitiesOnePosthogActionsMax = 32+export const canvasesValidateCreateBodyProjectOneCapabilitiesOneNetworkOriginsItemMax = 2048export const canvasesValidateCreateBodyProjectOneCapabilitiesOneNetworkOriginsMax = 20@@ -585,6 +639,24 @@ export const CanvasesValidateCreateBody = /* @__PURE__ */ zod)).max(canvasesValidateCreateBodyProjectOneCapabilitiesOnePosthogCaptureEventsMax),+ state: zod+ .array(zod.enum(['user', 'shared']).describe('\* `user` - user\n\* `shared` - shared'))+ .max(canvasesValidateCreateBodyProjectOneCapabilitiesOnePosthogStateMax)+ .optional()+ .describe(+ "State scopes the canvas may use via ph.state: 'user' (private to each viewer) and\/or 'shared' (one value per canvas, team-visible)."+ ),+ actions: zod+ .array(+ zod+ .string()+ .max(canvasesValidateCreateBodyProjectOneCapabilitiesOnePosthogActionsItemMax)+ )+ .max(canvasesValidateCreateBodyProjectOneCapabilitiesOnePosthogActionsMax)+ .optional()+ .describe(+ "Registered action verbs the canvas may invoke via ph.actions (e.g. 'annotations.create', 'tasks.create'). Each executes as the viewer; declaring one shows it in the promote review."+ ),}),network: zod.object({origins: zoddiff --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 e119da26d546..37d85f33003e 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@@ -70,6 +70,15 @@},"posthog": {"properties": {+ "actions": {+ "description": "Registered action verbs the canvas may invoke via ph.actions (e.g. 'annotations.create', 'tasks.create'). Each executes as the viewer; declaring one shows it in the promote review.",+ "items": {+ "maxLength": 64,+ "type": "string"+ },+ "maxItems": 32,+ "type": "array"+ },"captureEvents": {"items": {"maxLength": 200,@@ -88,6 +97,16 @@},"maxItems": 100,"type": "array"+ },+ "state": {+ "description": "State scopes the canvas may use via ph.state: 'user' (private to each viewer) and/or 'shared' (one value per canvas, team-visible).",+ "items": {+ "description": "* `user` - user\n* `shared` - shared",+ "enum": ["user", "shared"],+ "type": "string"+ },+ "maxItems": 2,+ "type": "array"}},"required": ["insights", "inlineQueries", "captureEvents"],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 89d469a6c9af..126cb9212d30 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@@ -86,6 +86,15 @@},"posthog": {"properties": {+ "actions": {+ "description": "Registered action verbs the canvas may invoke via ph.actions (e.g. 'annotations.create', 'tasks.create'). Each executes as the viewer; declaring one shows it in the promote review.",+ "items": {+ "maxLength": 64,+ "type": "string"+ },+ "maxItems": 32,+ "type": "array"+ },"captureEvents": {"items": {"maxLength": 200,@@ -104,6 +113,16 @@},"maxItems": 100,"type": "array"+ },+ "state": {+ "description": "State scopes the canvas may use via ph.state: 'user' (private to each viewer) and/or 'shared' (one value per canvas, team-visible).",+ "items": {+ "description": "* `user` - user\n* `shared` - shared",+ "enum": ["user", "shared"],+ "type": "string"+ },+ "maxItems": 2,+ "type": "array"}},"required": ["insights", "inlineQueries", "captureEvents"],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 d0ea598a0dbb..8982ca030b75 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@@ -70,6 +70,15 @@},"posthog": {"properties": {+ "actions": {+ "description": "Registered action verbs the canvas may invoke via ph.actions (e.g. 'annotations.create', 'tasks.create'). Each executes as the viewer; declaring one shows it in the promote review.",+ "items": {+ "maxLength": 64,+ "type": "string"+ },+ "maxItems": 32,+ "type": "array"+ },"captureEvents": {"items": {"maxLength": 200,@@ -88,6 +97,16 @@},"maxItems": 100,"type": "array"+ },+ "state": {+ "description": "State scopes the canvas may use via ph.state: 'user' (private to each viewer) and/or 'shared' (one value per canvas, team-visible).",+ "items": {+ "description": "* `user` - user\n* `shared` - shared",+ "enum": ["user", "shared"],+ "type": "string"+ },+ "maxItems": 2,+ "type": "array"}},"required": ["insights", "inlineQueries", "captureEvents"],diff --git a/tach.toml b/tach.tomlindex 481b7f0b477a..4fe22a0a0263 100644--- a/tach.toml+++ b/tach.toml@@ -818,6 +818,8 @@ depends_on = ["posthog",# Sandbox provisioning (via the tasks facade) and the Channel FK canvases file into."products.tasks",+ # The annotations.create action verb (via the annotations facade).+ "products.annotations",]layer = "modules"