: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 lifecycle analytics events and activity log (#78945)
Peter Kirkham5002fa16905d
diff --git a/frontend/package.json b/frontend/package.jsonindex f091d3884b6c..88cf50e66cff 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -87,6 +87,7 @@"@posthog/products-apm": "workspace:*","@posthog/products-batch-exports": "workspace:*","@posthog/products-business-knowledge": "workspace:*",+ "@posthog/products-canvas": "workspace:*","@posthog/products-cohorts": "workspace:*","@posthog/products-conversations": "workspace:*","@posthog/products-customer-analytics": "workspace:*",diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 63d10d8d7efc..ea086905b5b2 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -7085,7 +7085,7 @@ snapshots:scenes-app-settings-authentication-domains--one-unverified-domain--dark:hash: v1.k794b7964.d2354aea8e40abfcfeb18691d15e48abc24724460dbc0118185c750d3f8ce6d1.Gcj1tCTTgepeyP-Ep4JIhieodM8RlFeAjTQGNkP2UeQscenes-app-settings-authentication-domains--one-unverified-domain--light:- hash: v1.k794b7964.0c40bb5374be5247d5c0e2d73a2118c34d8083775cce447d3faf00ab4012f187.rqLTqwCSkMm5b7tey65wa2ycrn4lTsv8Rw4ASlNuCKs+ hash: v1.k794b7964.826b954e1c03e3156d0c10598975c3fd43583672372c163fa08264506f929cd7.C22X_4g68JpmDtmjwe33M24AQZ4CTTIwW2cMZPL0JCoscenes-app-settings-environment--settings-environment-access-control--dark:hash: v1.k794b7964.cdbb2694b5d5524628e578f807f3282a0e458c45172c29b79e2b6e7c06eac09f.HqYn6cyhm9cm_fXbavd2nlYeqoTVNd7ODjvCMKlAsIcscenes-app-settings-environment--settings-environment-access-control--light:diff --git a/frontend/src/lib/components/ActivityLog/activityLogLogic.test.setup.ts b/frontend/src/lib/components/ActivityLog/activityLogLogic.test.setup.tsindex a322b3f542ca..dcdd934e92b4 100644--- a/frontend/src/lib/components/ActivityLog/activityLogLogic.test.setup.ts+++ b/frontend/src/lib/components/ActivityLog/activityLogLogic.test.setup.ts@@ -7,6 +7,11 @@ import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'import { ActivityScope } from '~/types'+// The first test in each suite pays the one-time dynamic import of the+// describers registry — every product's describer and its dependency graph —+// which can exceed jest's 5s default on a loaded CI runner.+jest.setTimeout(15000)+interface APIMockSetup {name: stringactivity: stringdiff --git a/frontend/src/lib/components/ActivityLog/describers.tsx b/frontend/src/lib/components/ActivityLog/describers.tsxindex e760ff12aaf1..46f0e5e0bb8e 100644--- a/frontend/src/lib/components/ActivityLog/describers.tsx+++ b/frontend/src/lib/components/ActivityLog/describers.tsx@@ -41,6 +41,7 @@ import { ActivityScope } from '~/types'import { promptActivityDescriber } from 'products/ai_observability/frontend/prompts/promptActivityDescriber'import { promptLabelActivityDescriber } from 'products/ai_observability/frontend/prompts/promptLabelActivityDescriber'import { alertConfigurationActivityDescriber } from 'products/alerts/frontend/components/activityDescriptions'+import { canvasActivityDescriber } from 'products/canvas/frontend/activityDescriber'import { ticketActivityDescriber } from 'products/conversations/frontend/activityDescriber'import { externalDataSourceActivityDescriber } from 'products/data_warehouse/frontend/shared/components/activityDescriptions'import { endpointActivityDescriber } from 'products/endpoints/frontend/activityDescriber'@@ -61,6 +62,8 @@ export const describerFor = (logItem?: ActivityLogItem): Describer | undefined =return batchImportActivityDescribercase ActivityScope.BILLING:return billingActivityDescriber+ case ActivityScope.CANVAS:+ return canvasActivityDescribercase ActivityScope.EXPORTED_ASSET:return exportedAssetActivityDescribercase ActivityScope.DASHBOARD:diff --git a/frontend/src/lib/components/ActivityLog/humanizeActivity.tsx b/frontend/src/lib/components/ActivityLog/humanizeActivity.tsxindex f20a1c5e35b8..66c601f394ca 100644--- a/frontend/src/lib/components/ActivityLog/humanizeActivity.tsx+++ b/frontend/src/lib/components/ActivityLog/humanizeActivity.tsx@@ -165,6 +165,7 @@ const NO_PLURAL_SCOPES: ActivityScope[] = [ActivityScope.DATA_MANAGEMENT]const SCOPE_DISPLAY_NAMES: Partial<Record<ActivityScope, { singular: string; plural: string }>> = {[ActivityScope.ALERT_CONFIGURATION]: { singular: 'Alert', plural: 'Alerts' },[ActivityScope.BATCH_EXPORT]: { singular: 'Destination', plural: 'Destinations' },+ [ActivityScope.CANVAS]: { singular: 'Canvas', plural: 'Canvases' },[ActivityScope.EXTERNAL_DATA_SOURCE]: { singular: 'Source', plural: 'Sources' },[ActivityScope.HOG_FUNCTION]: { singular: 'Data pipeline', plural: 'Data pipelines' },[ActivityScope.PERSONAL_API_KEY]: { singular: 'Personal API key', plural: 'Personal API keys' },diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 2b163978349f..40b0b9560b28 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -6002,6 +6002,7 @@ export enum ActivityScope {EVENT_DEFINITION = 'EventDefinition',PROPERTY_DEFINITION = 'PropertyDefinition',NOTEBOOK = 'Notebook',+ CANVAS = 'Canvas',DASHBOARD = 'Dashboard',REPLAY = 'Replay',// TODO: doh! we don't need replay and recordingdiff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 00bfc24669bd..02cec4ff0119 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -659,6 +659,9 @@ importers:'@posthog/products-business-knowledge':specifier: workspace:*version: link:../products/business_knowledge+ '@posthog/products-canvas':+ specifier: workspace:*+ version: link:../products/canvas'@posthog/products-cohorts':specifier: workspace:*version: link:../products/cohorts@@ -2527,7 +2530,24 @@ importers:specifier: 18.3.1version: 18.3.1- products/canvas: {}+ products/canvas:+ dependencies:+ '@types/react':+ specifier: 18.3.27+ version: 18.3.27+ react:+ specifier: 18.3.1+ version: 18.3.1+ react-dom:+ specifier: 18.3.1+ version: 18.3.1([email protected])+ devDependencies:+ '@testing-library/react':+ specifier: ^14.3.1+ version: 14.3.1(@types/[email protected])([email protected]([email protected]))([email protected])+ jest:+ specifier: ^29.7.0+ version: 29.7.0(@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected]))products/cdp: {}diff --git a/posthog/api/advanced_activity_logs/viewset.py b/posthog/api/advanced_activity_logs/viewset.pyindex 787e71acfda6..bbfe720a8663 100644--- a/posthog/api/advanced_activity_logs/viewset.py+++ b/posthog/api/advanced_activity_logs/viewset.py@@ -100,6 +100,32 @@ def restrict_loop_activity_for_org(queryset: QuerySet[ActivityLog], organizationreturn queryset.exclude(Q(scope="Loop") & Q(item_id__in=hidden_ids))+def restrict_canvas_activity(queryset: QuerySet[ActivityLog], team_id: int, user) -> QuerySet[ActivityLog]:+ """Keep personal-channel canvases' metadata out of the team-wide activity feed.++ Canvas activity is team-scoped in the log, but a canvas in a personal channel is+ owner-only (see `CanvasViewSet`). Restrict `Canvas`-scoped rows to canvases this+ user may actually see. Lazy import keeps the canvas product off this module's path.+ """+ from products.canvas.backend import activity_visibility as canvas_activity # noqa: PLC0415++ visible_ids = canvas_activity.visible_canvas_ids(team_id, user)+ return queryset.exclude(Q(scope="Canvas") & ~Q(item_id__in=visible_ids))+++def restrict_canvas_activity_for_org(queryset: QuerySet[ActivityLog], organization_id, user) -> QuerySet[ActivityLog]:+ """Org-wide equivalent of `restrict_canvas_activity`. The org route has no single+ `team_id`, so deny other users' personal-channel canvas rows across the org. Canvases+ are soft-deleted, so their visibility stays computable without a persisted snapshot.+ """+ from products.canvas.backend import activity_visibility as canvas_activity # noqa: PLC0415++ hidden_ids = canvas_activity.hidden_personal_canvas_ids_for_org(organization_id, user)+ if not hidden_ids:+ return queryset+ return queryset.exclude(Q(scope="Canvas") & Q(item_id__in=hidden_ids))++def apply_organization_scoped_filter(queryset: QuerySet[ActivityLog], include_org_scoped: bool, team_id: int, organization_id) -> QuerySet[ActivityLog]:@@ -312,6 +338,7 @@ class ActivityLogViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet, mixinsqueryset = apply_activity_visibility_restrictions(queryset, self.request.user)queryset = restrict_loop_activity(queryset, self.team_id, self.request.user)+ queryset = restrict_canvas_activity(queryset, self.team_id, self.request.user)return queryset@@ -597,6 +624,7 @@ class AdvancedActivityLogsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSequeryset = apply_activity_visibility_restrictions(queryset, self.request.user)queryset = restrict_loop_activity(queryset, self.team_id, self.request.user)+ queryset = restrict_canvas_activity(queryset, self.team_id, self.request.user)return queryset.order_by(*activity_log_ordering(self.request))@@ -761,6 +789,7 @@ class OrganizationAdvancedActivityLogsViewSet(AdvancedActivityLogsViewSet):queryset = apply_activity_visibility_restrictions(queryset, self.request.user)# Org route: no single team_id (this endpoint is org-nested), so use the org-wide variant.queryset = restrict_loop_activity_for_org(queryset, self.organization.id, self.request.user)+ queryset = restrict_canvas_activity_for_org(queryset, self.organization.id, self.request.user)return queryset.order_by(*activity_log_ordering(self.request))diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.pyindex fafd9ac01a48..736df80099d1 100644--- a/posthog/models/activity_logging/activity_log.py+++ b/posthog/models/activity_logging/activity_log.py@@ -39,6 +39,7 @@ ActivityScope = Literal["EventDefinition","PropertyDefinition","Notebook",+ "Canvas","Endpoint","EndpointVersion","Dashboard",diff --git a/products/canvas/backend/activity_visibility.py b/products/canvas/backend/activity_visibility.pynew file mode 100644index 000000000000..04465d7d1cf9--- /dev/null+++ b/products/canvas/backend/activity_visibility.py@@ -0,0 +1,41 @@+"""Canvas activity-log visibility, mirroring products.tasks loops.++Canvas activity rows are team-scoped in the log, but a canvas filed in a personal+channel is owner-only (`CanvasViewSet` filters every action through the tasks+facade's `visible_channels_q`). Without these filters a teammate with activity-log+access could read another member's personal-canvas names, ids, and declared capabilities+out of the team- or org-wide feed. Canvases are soft-deleted (the row persists), so+visibility stays computable from the `Canvas` table without snapshotting context.+"""++from uuid import UUID++from posthog.models.user import User++from products.canvas.backend.models import Canvas+from products.tasks.backend.facade import api as tasks_facade+++def visible_canvas_ids(team_id: int, user: User | None) -> set[str]:+ """Ids (as strings) of this team's canvases whose channel the user may see.++ Used to restrict `Canvas`-scoped rows in the team activity feed; a canvas hidden+ from `CanvasViewSet` must not leak its history here either. Includes soft-deleted+ canvases so an owner still sees their deleted canvas's history.+ """+ user_id = getattr(user, "id", None)+ canvases = Canvas.objects.for_team(team_id).filter(tasks_facade.visible_channels_q(user_id, relation="channel"))+ return {str(canvas_id) for canvas_id in canvases.values_list("id", flat=True)}+++def hidden_personal_canvas_ids_for_org(organization_id: str | UUID, user: User | None) -> set[str]:+ """Ids (as strings) of personal-channel canvases across an org NOT owned by `user`.++ The org-wide feed (org admins/owners) must still keep other people's personal+ canvases out. Cross-team by design, hence `unscoped()`.+ """+ user_id = getattr(user, "id", None)+ hidden = Canvas.objects.unscoped().filter(+ ~tasks_facade.visible_channels_q(user_id, relation="channel"), team__organization_id=organization_id+ )+ return {str(canvas_id) for canvas_id in hidden.values_list("id", flat=True)}diff --git a/products/canvas/backend/build_service.py b/products/canvas/backend/build_service.pyindex fc2c4f117677..6614b66ecdf9 100644--- a/products/canvas/backend/build_service.py+++ b/products/canvas/backend/build_service.py@@ -35,7 +35,11 @@ from django.utils import timezoneimport structlogfrom prometheus_client import Counter, Gauge, Histogram+from posthog.event_usage import groups+from posthog.models.activity_logging.activity_log import Change, Detail, log_activityfrom posthog.models.scoping import team_scope+from posthog.models.user import User+from posthog.ph_client import ph_background_capturefrom posthog.storage import object_storagefrom products.canvas.backend.contract import CANVAS_BUILDER_DIR, contract_limits@@ -400,14 +404,18 @@ def publish_source_project(has_expected_version: bool,expected_version_id: str | None,task_id: UUID | None,- created_by_id: int | None,+ created_by: User | None,+ was_impersonated: bool = False,) -> tuple[Canvas, CanvasSourceVersion, CanvasBuild, bool]:"""Publish a validated project as the canvas's new head version.Upload-then-commit: the immutable source object goes up before thetransaction, so a conflicting publish leaves at most an unreferenced- upload. Returns (canvas, version, build, first_publish). Raises- CanvasVersionConflict, CanvasBuildCapacityExceeded, or ObjectStorageError.+ upload. Writes the "published" activity-log entry here (not in the API+ layer) so every caller is audited and the capabilities diff is computed+ against the head this publish actually replaced. Returns (canvas,+ version, build, first_publish). Raises CanvasVersionConflict,+ CanvasBuildCapacityExceeded, or ObjectStorageError."""# Lock-free fail-fast: reject a doomed publish before paying for the# upload. Its answer can go stale before the commit transaction re-checks@@ -459,7 +467,8 @@ def publish_source_project(source_size=size,task_id=task_id,prompt=prompt or None,- created_by_id=created_by_id,+ created_by=created_by,+ capabilities=project.get("capabilities") or {},)build = _queue_build(version)@@ -472,11 +481,47 @@ def publish_source_project(update_fields.append("name")canvas.save(update_fields=update_fields)+ # The pre-publish capabilities come from the parent version the claim+ # recorded under the head lock — exact even against a concurrent publish,+ # unlike a read taken before the transaction. None means "predates the+ # snapshot", not "empty".+ previous_capabilities = (+ CanvasSourceVersion.objects.for_team(canvas.team_id)+ .filter(pk=version.parent_version_id)+ .values_list("capabilities", flat=True)+ .first()+ if version.parent_version_id+ else None+ )+ changes = None+ if previous_capabilities != version.capabilities:+ changes = [+ Change(+ type="Canvas",+ action="changed",+ field="capabilities",+ before=previous_capabilities,+ after=version.capabilities,+ )+ ]+ _log_canvas_activity(+ canvas,+ user=created_by,+ was_impersonated=was_impersonated,+ activity="published",+ detail=Detail(name=canvas.name, changes=changes),+ )+return canvas, version, build, first_publishdef revert_to_version(- canvas: Canvas, version_id: str | UUID, expected_current_version_id: str | UUID | None+ canvas: Canvas,+ version_id: str | UUID,+ expected_current_version_id: str | UUID | None,+ *,+ user: User | None = None,+ was_impersonated: bool = False,) -> tuple[Canvas, CanvasBuild]:"""Move the canvas's head back to an existing version and rebuild it.@@ -485,13 +530,47 @@ def revert_to_version("""with transaction.atomic(), team_scope(canvas.team_id):canvas = _claim_canvas_head(canvas, has_expected_version=True, expected_version_id=expected_current_version_id)+ previous_head_id = str(canvas.current_source_version_id) if canvas.current_source_version_id else Noneversion = CanvasSourceVersion.objects.for_team(canvas.team_id).get(pk=version_id, canvas_id=canvas.id)canvas.current_source_version = versioncanvas.save(update_fields=["current_source_version", "updated_at"])build = _queue_build(version)+ _log_canvas_activity(+ canvas,+ user=user,+ was_impersonated=was_impersonated,+ activity="reverted",+ detail=Detail(+ name=canvas.name,+ changes=[+ Change(+ type="Canvas",+ action="changed",+ field="current_source_version",+ before=previous_head_id,+ after=str(version.id),+ )+ ],+ ),+ )return canvas, build+def _log_canvas_activity(+ canvas: Canvas, *, user: User | None, was_impersonated: bool, activity: str, detail: Detail+) -> None:+ log_activity(+ organization_id=canvas.team.organization_id,+ team_id=canvas.team_id,+ user=user,+ was_impersonated=was_impersonated,+ item_id=canvas.id,+ scope="Canvas",+ activity=activity,+ detail=detail,+ )++def act_on_build(canvas: Canvas, build_id: str | UUID, action: str) -> CanvasBuild:"""Apply a lifecycle action (retry, pin, unpin, cancel) to one build.@@ -672,6 +751,46 @@ def run_canvas_build(team_id: int, build_id: str) -> None:max(0, ((build.finished_at or timezone.now()) - build.created_at).total_seconds()))CANVAS_BUILD_ARTIFACT_BYTES.observe(sum(asset["sizeBytes"] for asset in manifest["assets"]))+ _capture_build_completed(build, outcome="ready")+++def _capture_build_completed(build: CanvasBuild, *, outcome: str) -> None:+ """Product-analytics record of a terminal build, attributed to the version's+ publisher when there is one. Diagnostics contribute codes only — messages can+ quote source. Deferred to commit so no network work runs while a caller's+ transaction still holds row locks, and delivered through the background+ client (no per-call setup or blocking flush). Telemetry must never fail a+ build, so errors are swallowed.+ """++ def send() -> None:+ try:+ team = build.team+ user = build.source_version.created_by+ duration_seconds = max(0, ((build.finished_at or timezone.now()) - build.created_at).total_seconds())+ error_codes = [+ str(item.get("code"))+ for item in (build.diagnostics or [])+ if isinstance(item, dict) and item.get("severity") == "error"+ ][:10]+ ph_background_capture()(+ distinct_id=user.distinct_id if user else str(team.uuid),+ event="canvas build completed",+ properties={+ "canvas_id": str(build.canvas_id),+ "build_id": str(build.id),+ "source_version_id": str(build.source_version_id),+ "outcome": outcome,+ "attempt_count": build.attempt_count,+ "duration_seconds": round(duration_seconds, 2),+ "error_codes": error_codes,+ },+ groups=groups(team.organization, team),+ )+ except Exception:+ logger.warning("canvas_build_capture_failed", build_id=str(build.id), exc_info=True)++ transaction.on_commit(send)def _finalize_ready(@@ -779,6 +898,7 @@ def _finish_failed(stale_build: CanvasBuild, diagnostics: list[dict[str, Any]])CANVAS_BUILD_DURATION_SECONDS.labels(outcome="failed").observe(max(0, (build.finished_at - build.created_at).total_seconds()))+ _capture_build_completed(build, outcome="failed")def sweep_canvas_builds() -> dict[str, int]:diff --git a/products/canvas/backend/migrations/0009_canvassourceversion_capabilities.py b/products/canvas/backend/migrations/0009_canvassourceversion_capabilities.pynew file mode 100644index 000000000000..8a7cceb8d7b7--- /dev/null+++ b/products/canvas/backend/migrations/0009_canvassourceversion_capabilities.py@@ -0,0 +1,15 @@+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("canvas", "0008_remove_home_canvas"),+ ]++ operations = [+ migrations.AddField(+ model_name="canvassourceversion",+ name="capabilities",+ field=models.JSONField(blank=True, null=True),+ ),+ ]diff --git a/products/canvas/backend/migrations/max_migration.txt b/products/canvas/backend/migrations/max_migration.txtindex 4b4ca0731778..c8eb8fb45d76 100644--- a/products/canvas/backend/migrations/max_migration.txt+++ b/products/canvas/backend/migrations/max_migration.txt@@ -1 +1 @@-0008_remove_home_canvas+0009_canvassourceversion_capabilitiesdiff --git a/products/canvas/backend/models.py b/products/canvas/backend/models.pyindex 92491e4b12c9..61be0ac7a706 100644--- a/products/canvas/backend/models.py+++ b/products/canvas/backend/models.py@@ -81,6 +81,11 @@ class CanvasSourceVersion(TeamScopedRootMixin, UUIDModel):task_run_id = models.UUIDField(null=True, blank=True)prompt = models.TextField(null=True, blank=True)+ # Snapshot of the project's declared capabilities manifest, denormalized+ # from the stored source so capability changes can be diffed and audited+ # without reading object storage. Null for versions that predate it.+ capabilities = models.JSONField(null=True, blank=True)+created_by = models.ForeignKey("posthog.User", on_delete=models.SET_NULL, null=True, blank=True, db_constraint=False)diff --git a/products/canvas/backend/presentation/views.py b/products/canvas/backend/presentation/views.pyindex 840bb6903f23..cdc74d2c7ccf 100644--- a/products/canvas/backend/presentation/views.py+++ b/products/canvas/backend/presentation/views.py@@ -15,6 +15,9 @@ from rest_framework.response import Responsefrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.auth import OAuthAccessTokenAuthentication+from posthog.event_usage import report_user_action+from posthog.helpers.impersonation import is_impersonated+from posthog.models.activity_logging.activity_log import Change, Detail, Trigger, log_activityfrom posthog.models.user import Userfrom posthog.storage.object_storage import ObjectStorageErrorfrom posthog.temporal.oauth import SANDBOX_OAUTH_APP_CLIENT_IDS@@ -160,6 +163,13 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):# generations have no client-side create to record it.generation_task_id=self._sandbox_task_id(request),)+ self._log_canvas_activity(canvas, "created", Detail(name=canvas.name))+ self._report_canvas_action(+ "canvas created",+ canvas,+ template_id=canvas.template_id,+ is_sandbox_created=canvas.generation_task_id is not None,+ )return Response(CanvasSerializer(canvas).data, status=status.HTTP_201_CREATED)@extend_schema(@@ -174,13 +184,27 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):payload.is_valid(raise_exception=True)data = payload.validated_dataupdate_fields = ["updated_at"]+ changes: list[Change] = []++ def record(field: str, before: Any = None, after: Any = None) -> None:+ changes.append(Change(type="Canvas", action="changed", field=field, before=before, after=after))+if "name" in data:+ if data["name"] != canvas.name:+ record("name", canvas.name, data["name"])canvas.name = data["name"]update_fields.append("name")if "context" in data:+ # The author-context markdown is content, not configuration — record+ # that it changed without copying it into the audit trail.+ if data["context"] != canvas.context:+ record("context")canvas.context = data["context"]update_fields.append("context")if "pinned" in data:+ was_pinned = canvas.pinned_at is not None+ if data["pinned"] != was_pinned:+ record("pinned", was_pinned, data["pinned"])canvas.pinned_at = timezone.now() if data["pinned"] else Noneupdate_fields.append("pinned_at")if "generation_task_id" in data:@@ -193,11 +217,15 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):canvas.generation_task_id = task_idupdate_fields.append("generation_task_id")canvas.save(update_fields=update_fields)+ if changes:+ self._log_canvas_activity(canvas, "updated", Detail(name=canvas.name, changes=changes))return Response(CanvasSerializer(canvas).data)def perform_destroy(self, instance: Canvas) -> None:instance.deleted = Trueinstance.save(update_fields=["deleted", "updated_at"])+ self._log_canvas_activity(instance, "deleted", Detail(name=instance.name))+ self._report_canvas_action("canvas deleted", instance)@extend_schema(operation_id="canvases_source_retrieve",@@ -399,7 +427,8 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):has_expected_version=has_expected_version,expected_version_id=expected_version_id,task_id=task_id,- created_by_id=user.id if user else None,+ created_by=user,+ was_impersonated=is_impersonated(request),)except build_service.CanvasVersionConflict as conflict:return _conflict_response(conflict)@@ -414,6 +443,20 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):if first_publish:self._announce_canvas_created(task_id, user, canvas)+ posthog_capabilities = (version.capabilities or {}).get("posthog") or {}+ self._report_canvas_action(+ "canvas published",+ canvas,+ version_id=str(version.id),+ first_publish=first_publish,+ file_count=len(project.get("files") or {}),+ source_size_bytes=version.source_size,+ insight_capability_count=len(posthog_capabilities.get("insights") or []),+ capture_event_capability_count=len(posthog_capabilities.get("captureEvents") or []),+ inline_queries_capability=bool(posthog_capabilities.get("inlineQueries")),+ is_sandbox_publish=task_id is not None,+ )+return Response({"canvas": CanvasSummarySerializer(canvas).data,@@ -437,10 +480,12 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):payload = CanvasRevertSerializer(data=request.data)payload.is_valid(raise_exception=True)try:- _canvas, build = build_service.revert_to_version(+ canvas, build = build_service.revert_to_version(canvas,payload.validated_data["version_id"],payload.validated_data["expected_current_version_id"],+ user=self._request_user(),+ was_impersonated=is_impersonated(request),)except build_service.CanvasVersionConflict as conflict:return _conflict_response(conflict)@@ -448,6 +493,7 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):return _capacity_response()except CanvasSourceVersion.DoesNotExist:return Response({"detail": "Version not found for this canvas."}, status=status.HTTP_404_NOT_FOUND)+ self._report_canvas_action("canvas reverted", canvas, version_id=str(payload.validated_data["version_id"]))return Response(CanvasBuildSerializer(build).data)@extend_schema(@@ -525,8 +571,43 @@ class CanvasViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):return _capacity_response()except ValueError as error:return Response({"detail": str(error)}, status=status.HTTP_400_BAD_REQUEST)+ self._log_canvas_activity(+ canvas,+ f"build_{payload.validated_data['action']}",+ Detail(+ name=canvas.name,+ trigger=Trigger(+ job_type="canvas_build",+ job_id=str(build.id),+ payload={"action": payload.validated_data["action"]},+ ),+ ),+ )return Response(CanvasBuildSerializer(build).data)+ def _log_canvas_activity(self, canvas: Canvas, activity: str, detail: Detail) -> None:+ log_activity(+ organization_id=self.team.organization_id,+ team_id=self.team.pk,+ user=self._request_user(),+ was_impersonated=is_impersonated(self.request),+ item_id=canvas.id,+ scope="Canvas",+ activity=activity,+ detail=detail,+ )++ def _report_canvas_action(self, event: str, canvas: Canvas, **extra: Any) -> None:+ user = self._request_user()+ if user:+ report_user_action(+ user,+ event,+ {"canvas_id": str(canvas.id), "channel_id": str(canvas.channel_id), **extra},+ team=self.team,+ request=self.request,+ )+def _request_user(self) -> User | None:"""The requesting real user, or None for anonymous/service principals."""user = self.request.userdiff --git a/products/canvas/backend/tests/test_build_service.py b/products/canvas/backend/tests/test_build_service.pyindex edc8ca08f74f..c3deb67a175f 100644--- a/products/canvas/backend/tests/test_build_service.py+++ b/products/canvas/backend/tests/test_build_service.py@@ -7,6 +7,8 @@ from unittest.mock import patchfrom django.test import override_settingsfrom django.utils import timezone+from parameterized import parameterized+from posthog.models.scoping import team_scopefrom products.canvas.backend import build_service@@ -63,7 +65,7 @@ class BuildServiceBaseTest(APIBaseTest):has_expected_version=False,expected_version_id=None,task_id=None,- created_by_id=None,+ created_by=None,)self.canvas.refresh_from_db()return build@@ -188,6 +190,35 @@ class TestRunCanvasBuild(BuildServiceBaseTest):assert build.status == CanvasBuild.STATUS_FAILEDassert self.canvas.published_build_id is None+ @parameterized.expand(+ [+ ("ready", _builder_result({"index.html": "<html></html>"}), []),+ (+ "failed",+ {+ "contractVersion": 1,+ "status": "failed",+ "diagnostics": [{"severity": "error", "code": "bundle_error", "message": "boom"}],+ },+ ["bundle_error"],+ ),+ ]+ )+ def test_terminal_build_captures_its_outcome(self, outcome: str, builder_result: dict, error_codes: list[str]):+ # The capture is wrapped in a catch-all so telemetry never fails a build, which+ # would let a broken payload lose the event silently.+ build = self._publish()+ with patch.object(build_service, "ph_background_capture") as capture:+ with self.captureOnCommitCallbacks(execute=True):+ with patch.object(build_service, "run_cloud_builder", return_value=builder_result):+ build_service.run_canvas_build(self.team.id, str(build.id))++ properties = capture.return_value.call_args.kwargs["properties"]+ assert capture.return_value.call_args.kwargs["event"] == "canvas build completed"+ assert properties["outcome"] == outcome+ assert properties["error_codes"] == error_codes+ assert properties["build_id"] == str(build.id)+class TestSweeper(BuildServiceBaseTest):def test_lease_expired_building_is_requeued_then_failed(self):@@ -317,7 +348,7 @@ class TestLegacySourcePreservation(BuildServiceBaseTest):has_expected_version=True,expected_version_id=None,task_id=None,- created_by_id=None,+ created_by=None,)head = CanvasSourceVersion.objects.unscoped().get(pk=version.id)diff --git a/products/canvas/backend/tests/test_canvas_api.py b/products/canvas/backend/tests/test_canvas_api.pyindex c0a4de271f01..7dac511ed4e3 100644--- a/products/canvas/backend/tests/test_canvas_api.py+++ b/products/canvas/backend/tests/test_canvas_api.py@@ -6,9 +6,10 @@ from unittest.mock import patchfrom rest_framework import status+from posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.scoping import team_scope-from products.canvas.backend import build_service+from products.canvas.backend import activity_visibility, build_servicefrom products.canvas.backend.models import Canvas, CanvasBuild, CanvasSourceVersionfrom products.canvas.backend.source import synthetic_source_projectfrom products.tasks.backend.models import Channel@@ -483,3 +484,117 @@ class TestCanvasRevertAndBuilds(CanvasAPIBaseTest):act("cancel")with patch.object(build_service, "MAX_ACTIVE_CANVAS_BUILDS_PER_TEAM", 0):assert act("retry").status_code == status.HTTP_429_TOO_MANY_REQUESTS+++class TestCanvasActivityLog(CanvasAPIBaseTest):+ def _activity(self, activity: str) -> list[ActivityLog]:+ return list(+ ActivityLog.objects.filter(team_id=self.team.id, scope="Canvas", activity=activity).order_by("created_at")+ )++ def _changes(self, entry: ActivityLog) -> list[dict[str, Any]]:+ assert entry.detail is not None+ return entry.detail["changes"]++ def test_publish_snapshots_capabilities_and_logs_the_diff(self):+ canvas_id = self._create_canvas()+ first = self._publish(canvas_id, expected_current_version_id=None)+ assert first.status_code == status.HTTP_200_OK, first.json()++ default_capabilities = {+ "posthog": {"insights": [], "inlineQueries": False, "captureEvents": []},+ "network": {"origins": []},+ }+ widened_capabilities = {+ "posthog": {"insights": ["abc123"], "inlineQueries": True, "captureEvents": []},+ "network": {"origins": []},+ }+ widened = self._project("export default function C() { return 2 }")+ widened["capabilities"] = widened_capabilities+ second = self._publish(canvas_id, widened, expected_current_version_id=first.json()["current_version_id"])+ assert second.status_code == status.HTTP_200_OK, second.json()++ versions = CanvasSourceVersion.objects.unscoped().filter(canvas_id=canvas_id).order_by("created_at")+ assert [version.capabilities for version in versions] == [default_capabilities, widened_capabilities]++ entries = self._activity("published")+ assert len(entries) == 2+ assert entries[0].user == self.user+ changes = self._changes(entries[1])+ assert len(changes) == 1+ assert changes[0]["field"] == "capabilities"+ assert changes[0]["before"] == default_capabilities+ assert changes[0]["after"] == widened_capabilities++ def test_revert_logs_the_head_move(self):+ canvas_id = self._create_canvas()+ first = self._publish(canvas_id, expected_current_version_id=None)+ v1 = first.json()["current_version_id"]+ second = self._publish(+ canvas_id,+ self._project("export default function C() { return 2 }"),+ expected_current_version_id=v1,+ )+ v2 = second.json()["current_version_id"]+ response = self.client.post(+ f"/api/projects/{self.team.id}/canvases/{canvas_id}/revert/",+ {"version_id": v1, "expected_current_version_id": v2},+ format="json",+ )+ assert response.status_code == status.HTTP_200_OK, response.json()++ entries = self._activity("reverted")+ assert len(entries) == 1+ changes = self._changes(entries[0])+ assert changes[0]["field"] == "current_source_version"+ assert changes[0]["before"] == v2+ assert changes[0]["after"] == v1++ def test_rename_logs_a_change_but_a_no_op_update_does_not(self):+ canvas_id = self._create_canvas()+ base = f"/api/projects/{self.team.id}/canvases/{canvas_id}"++ response = self.client.patch(f"{base}/", {"name": "Renamed"}, format="json")+ assert response.status_code == status.HTTP_200_OK+ entries = self._activity("updated")+ assert len(entries) == 1+ assert self._changes(entries[0]) == [+ {"type": "Canvas", "action": "changed", "field": "name", "before": "My canvas", "after": "Renamed"}+ ]++ response = self.client.patch(f"{base}/", {"name": "Renamed"}, format="json")+ assert response.status_code == status.HTTP_200_OK+ assert len(self._activity("updated")) == 1+++class TestCanvasActivityVisibility(CanvasAPIBaseTest):+ """Personal-channel canvases are owner-only, so their team-scoped activity rows must+ not leak to other members through the team- or org-wide activity feed."""++ def _personal_canvas(self, owner) -> Canvas:+ with team_scope(self.team.id):+ channel = Channel.objects.create(+ team=self.team, name="me", channel_type=Channel.ChannelType.PERSONAL, created_by=owner+ )+ return Canvas.objects.create(team_id=self.team.id, channel=channel, name="Private", created_by=owner)++ def test_team_visible_ids_include_public_but_hide_others_personal_canvas(self):+ other = self._create_user("[email protected]")+ private = self._personal_canvas(self.user)+ public_id = self._create_canvas(name="Public")++ owner_visible = activity_visibility.visible_canvas_ids(self.team.id, self.user)+ other_visible = activity_visibility.visible_canvas_ids(self.team.id, other)++ assert {public_id, str(private.id)} <= owner_visible+ assert public_id in other_visible+ assert str(private.id) not in other_visible++ def test_org_hidden_ids_exclude_owner_but_include_other_members(self):+ other = self._create_user("[email protected]")+ private = self._personal_canvas(self.user)++ assert str(private.id) not in activity_visibility.hidden_personal_canvas_ids_for_org(+ self.organization.id, self.user+ )+ assert str(private.id) in activity_visibility.hidden_personal_canvas_ids_for_org(self.organization.id, other)diff --git a/products/canvas/frontend/activityDescriber.test.tsx b/products/canvas/frontend/activityDescriber.test.tsxnew file mode 100644index 000000000000..c47dd07f8308--- /dev/null+++ b/products/canvas/frontend/activityDescriber.test.tsx@@ -0,0 +1,121 @@+import { render } from '@testing-library/react'++import { ActivityChange, ActivityLogItem } from 'lib/components/ActivityLog/humanizeActivity'++import { ActivityScope } from '~/types'++import { canvasActivityDescriber } from './activityDescriber'++const getTextContent = (describer: { description: JSX.Element | string | null }): string => {+ if (!describer.description || typeof describer.description === 'string') {+ return (describer.description as string) || ''+ }+ const { container } = render(describer.description)+ return container.textContent || ''+}++const canvasLogItem = (overrides: Partial<ActivityLogItem>): ActivityLogItem => ({+ activity: 'published',+ created_at: '2026-08-06T10:00:00Z',+ scope: 'Canvas',+ item_id: 'canvas-uuid',+ detail: { merge: null, trigger: null, changes: null, name: 'Signups board' },+ ...overrides,+})++const capabilitiesChange = (before: unknown, after: unknown): ActivityChange => ({+ type: ActivityScope.CANVAS,+ action: 'changed',+ field: 'capabilities',+ before: before as ActivityChange['before'],+ after: after as ActivityChange['after'],+})++describe('canvasActivityDescriber', () => {+ it('summarizes a first publish with a null previous manifest', () => {+ const text = getTextContent(+ canvasActivityDescriber(+ canvasLogItem({+ detail: {+ merge: null,+ trigger: null,+ name: 'Signups board',+ changes: [+ capabilitiesChange(null, {+ posthog: { insights: ['abc123'], inlineQueries: true, captureEvents: [] },+ }),+ ],+ },+ })+ )+ )+ expect(text).toContain('published canvas Signups board')+ expect(text).toContain('declared insight abc123')+ expect(text).toContain('enabled inline queries')+ })++ it('summarizes added and removed capabilities between two manifests', () => {+ const text = getTextContent(+ canvasActivityDescriber(+ canvasLogItem({+ detail: {+ merge: null,+ trigger: null,+ name: 'Signups board',+ changes: [+ capabilitiesChange(+ {+ posthog: {+ insights: ['abc123'],+ inlineQueries: true,+ captureEvents: ['clicked'],+ },+ },+ {+ posthog: {+ insights: ['def456'],+ inlineQueries: false,+ captureEvents: ['clicked'],+ },+ }+ ),+ ],+ },+ })+ )+ )+ expect(text).toContain('declared insight def456')+ expect(text).toContain('removed insight abc123')+ expect(text).toContain('disabled inline queries')+ expect(text).not.toContain('clicked')+ })++ it('describes a publish without capability changes as a plain publish', () => {+ const text = getTextContent(canvasActivityDescriber(canvasLogItem({})))+ expect(text).toContain('published canvas Signups board')+ expect(text).not.toContain('capabilities')+ })++ it.each([+ [+ 'name',+ { type: ActivityScope.CANVAS, action: 'changed', field: 'name', before: 'Old', after: 'New' },+ 'renamed it from Old to New',+ ],+ [+ 'pinned',+ { type: ActivityScope.CANVAS, action: 'changed', field: 'pinned', before: false, after: true },+ 'pinned it to its channel',+ ],+ ] as [string, ActivityChange, string][])('describes an update to %s', (_field, change, expected) => {+ const text = getTextContent(+ canvasActivityDescriber(+ canvasLogItem({+ activity: 'updated',+ detail: { merge: null, trigger: null, name: 'Signups board', changes: [change] },+ })+ )+ )+ expect(text).toContain(expected)+ })+})diff --git a/products/canvas/frontend/activityDescriber.tsx b/products/canvas/frontend/activityDescriber.tsxnew file mode 100644index 000000000000..613d26cf6ad7--- /dev/null+++ b/products/canvas/frontend/activityDescriber.tsx@@ -0,0 +1,155 @@+import {+ ActivityChange,+ ActivityLogItem,+ Description,+ HumanizedChange,+ defaultDescriber,+ userNameForLogItem,+} from 'lib/components/ActivityLog/humanizeActivity'++interface CanvasPostHogCapabilities {+ insights?: string[]+ captureEvents?: string[]+ inlineQueries?: boolean+}++function posthogCapabilities(value: unknown): CanvasPostHogCapabilities {+ if (value && typeof value === 'object' && 'posthog' in value) {+ return ((value as Record<string, unknown>).posthog ?? {}) as CanvasPostHogCapabilities+ }+ return {}+}++function listDiff(before: string[] | undefined, after: string[] | undefined): { added: string[]; removed: string[] } {+ const beforeSet = new Set(before ?? [])+ const afterSet = new Set(after ?? [])+ return {+ added: [...afterSet].filter((item) => !beforeSet.has(item)),+ removed: [...beforeSet].filter((item) => !afterSet.has(item)),+ }+}++export function describeCapabilitiesChange(change: ActivityChange): Description[] {+ const before = posthogCapabilities(change.before)+ const after = posthogCapabilities(change.after)+ const parts: Description[] = []++ const pushDiff = (verb: string, noun: string, items: string[]): void => {+ if (items.length > 0) {+ parts.push(+ <>+ {verb} {noun}+ {items.length === 1 ? '' : 's'} <strong>{items.join(', ')}</strong>+ </>+ )+ }+ }+ const insights = listDiff(before.insights, after.insights)+ pushDiff('declared', 'insight', insights.added)+ pushDiff('removed', 'insight', insights.removed)+ const events = listDiff(before.captureEvents, after.captureEvents)+ pushDiff('declared', 'capture event', events.added)+ pushDiff('removed', 'capture event', events.removed)++ if (!!before.inlineQueries !== !!after.inlineQueries) {+ parts.push(after.inlineQueries ? <>enabled inline queries</> : <>disabled inline queries</>)+ }++ return parts+}++const BUILD_ACTIVITY_COPY: Record<string, string> = {+ build_retry: 'retried a build of',+ build_pin: 'pinned a build of',+ build_unpin: 'unpinned a build of',+ build_cancel: 'canceled a build of',+}++const inlineOrList = (parts: Description[]): JSX.Element =>+ parts.length === 1 ? (+ <> {parts[0]}</>+ ) : (+ <ul className="bullet-list">+ {parts.map((part, index) => (+ <li key={index}>{part}</li>+ ))}+ </ul>+ )++const canvasUpdateFieldCopy = (change: ActivityChange): Description | null => {+ if (change.field === 'name') {+ return (+ <>+ renamed it from <strong>{change.before as string}</strong> to <strong>{change.after as string}</strong>+ </>+ )+ }+ if (change.field === 'pinned') {+ return change.after ? <>pinned it to its channel</> : <>unpinned it from its channel</>+ }+ if (change.field === 'context') {+ return <>updated its context</>+ }+ return null+}++export function canvasActivityDescriber(logItem: ActivityLogItem, asNotification?: boolean): HumanizedChange {+ if (logItem.scope !== 'Canvas') {+ console.error('canvas describer received a non-canvas activity')+ return { description: null }+ }++ const actor = <strong className="ph-no-capture">{userNameForLogItem(logItem)}</strong>+ const canvasName = <strong>{logItem.detail.name || 'Untitled canvas'}</strong>++ if (logItem.activity === 'published') {+ const capabilitiesChange = (logItem.detail.changes || []).find((change) => change.field === 'capabilities')+ const parts = capabilitiesChange ? describeCapabilitiesChange(capabilitiesChange) : []+ return {+ description: (+ <>+ {actor} published canvas {canvasName}+ {parts.length === 1 ? <> and</> : null}+ {parts.length > 1 ? <> and changed its declared capabilities:</> : null}+ {parts.length > 0 ? inlineOrList(parts) : null}+ </>+ ),+ }+ }++ if (logItem.activity === 'reverted') {+ return {+ description: (+ <>+ {actor} reverted canvas {canvasName} to an earlier version+ </>+ ),+ }+ }++ if (logItem.activity === 'updated') {+ const parts = (logItem.detail.changes || []).map(canvasUpdateFieldCopy).filter(Boolean) as Description[]+ if (parts.length > 0) {+ return {+ description: (+ <>+ {actor} updated canvas {canvasName}:{inlineOrList(parts)}+ </>+ ),+ }+ }+ }++ const buildCopy = BUILD_ACTIVITY_COPY[logItem.activity]+ if (buildCopy) {+ return {+ description: (+ <>+ {actor} {buildCopy} canvas {canvasName}+ </>+ ),+ }+ }++ return defaultDescriber(logItem, asNotification, canvasName)+}diff --git a/products/canvas/package.json b/products/canvas/package.jsonindex 1f1137bc4e01..8bf2572e0575 100644--- a/products/canvas/package.json+++ b/products/canvas/package.json@@ -5,5 +5,13 @@"backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests -v --tb=short"},"dependencies": {},- "devDependencies": {}+ "devDependencies": {+ "@testing-library/react": "^14.3.1",+ "jest": "^29.7.0"+ },+ "peerDependencies": {+ "@types/react": "*",+ "react": "*",+ "react-dom": "*"+ }}diff --git a/products/desktop/packages/shared/src/analytics-events.ts b/products/desktop/packages/shared/src/analytics-events.tsindex 7dffa2ea55bc..c5a720c032eb 100644--- a/products/desktop/packages/shared/src/analytics-events.ts+++ b/products/desktop/packages/shared/src/analytics-events.ts@@ -1047,6 +1047,26 @@ export interface CanvasPromptSentProperties {prompt_length_chars: number;}+export interface CanvasRenderedProperties {+ channel_id?: string;+ dashboard_id?: string;+ /** The published build whose artifact rendered; absent for head-source renders. */+ build_id?: string;+}++export interface CanvasRuntimeErrorProperties {+ channel_id?: string;+ dashboard_id?: string;+ /** The published build whose artifact threw; absent for head-source renders. */+ build_id?: string;+ /**+ * The error's class name (e.g. "TypeError"), or "unknown". Deliberately not the+ * raw message: canvas source is user/agent-authored and its exceptions can carry+ * source fragments, query results, or secrets that must not cross into analytics.+ */+ error_type: string;+}+export type ContextActionType = "save_version" | "generate_started" | "discard";export interface ContextActionProperties {@@ -1449,6 +1469,8 @@ export const ANALYTICS_EVENTS = {CHANNEL_ACTION: "Channel action",DASHBOARD_ACTION: "Dashboard action",CANVAS_PROMPT_SENT: "Canvas prompt sent",+ CANVAS_RENDERED: "Canvas rendered",+ CANVAS_RUNTIME_ERROR: "Canvas runtime error",CONTEXT_ACTION: "Context action",// Autoresearch events@@ -1628,6 +1650,8 @@ export type EventPropertyMap = {[ANALYTICS_EVENTS.CHANNEL_ACTION]: ChannelActionProperties;[ANALYTICS_EVENTS.DASHBOARD_ACTION]: DashboardActionProperties;[ANALYTICS_EVENTS.CANVAS_PROMPT_SENT]: CanvasPromptSentProperties;+ [ANALYTICS_EVENTS.CANVAS_RENDERED]: CanvasRenderedProperties;+ [ANALYTICS_EVENTS.CANVAS_RUNTIME_ERROR]: CanvasRuntimeErrorProperties;[ANALYTICS_EVENTS.CONTEXT_ACTION]: ContextActionProperties;// Autoresearch eventsdiff --git a/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsxindex ca3e2819082f..f961b53c139b 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsx+++ b/products/desktop/packages/ui/src/features/canvas/freeform/FreeformCanvasView.tsx@@ -31,6 +31,7 @@ import {EmptyTitle,} from "@posthog/quill";import { CANVAS_COMPONENT_PATH } from "@posthog/shared";+import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";import {isCanvasGenerating,isCanvasGenerationRunning,@@ -60,6 +61,7 @@ import { useSessionForTask } from "@posthog/ui/features/sessions/useSession";import { taskDetailQuery } from "@posthog/ui/features/tasks/queries";import { ResizableSidebar } from "@posthog/ui/primitives/ResizableSidebar";import { toast } from "@posthog/ui/primitives/toast";+import { track } from "@posthog/ui/shell/analytics";import {Box,Flex,@@ -96,6 +98,15 @@ import { usePinnedArtifact } from "./usePinnedArtifact";// history), and an edit composer. Generation runs as a dedicated task; while// one is in flight the empty canvas shows a "Generating…" state with the run's// chat panel open by default (in view mode too), so the work is watchable.+// The canvas runtime error string is user/agent-authored and can carry source+// fragments, query results, or secrets. Reduce it to the leading error class name+// (e.g. "TypeError") for analytics, so no interpolated content crosses the boundary.+function canvasErrorType(message: string): string {+ return (+ message.match(/^([A-Z][A-Za-z0-9]*(?:Error|Exception))\b/)?.[1] ?? "unknown"+ );+}+export function FreeformCanvasView({threadId,interactive,@@ -424,15 +435,38 @@ export function FreeformCanvasView({[queryClient],);+ // Dedupes the runtime-error capture without a store dependency: reading+ // runtimeError in the callbacks would change their identity on every+ // error set/clear, and the warm-frame pool assumes stable callbacks.+ const lastRuntimeErrorRef = useRef<string | null>(null);+ const canvasTrackProps = useMemo(+ () => ({+ channel_id: channelId || undefined,+ dashboard_id: dashboardId,+ build_id: pinnedArtifact?.buildId,+ }),+ [channelId, dashboardId, pinnedArtifact?.buildId],+ );const onError = useCallback(- (message: string) => setRuntimeError(threadId, message),- [threadId, setRuntimeError],+ (message: string) => {+ if (message !== lastRuntimeErrorRef.current) {+ lastRuntimeErrorRef.current = message;+ track(ANALYTICS_EVENTS.CANVAS_RUNTIME_ERROR, {+ ...canvasTrackProps,+ error_type: canvasErrorType(message),+ });+ }+ setRuntimeError(threadId, message);+ },+ [threadId, setRuntimeError, canvasTrackProps],);const onRendered = useCallback(() => {// "rendered" is as good as "ready" as proof the pinned artifact URL loaded.onArtifactReady();+ lastRuntimeErrorRef.current = null;setRuntimeError(threadId, null);- }, [threadId, setRuntimeError, onArtifactReady]);+ track(ANALYTICS_EVENTS.CANVAS_RENDERED, canvasTrackProps);+ }, [threadId, setRuntimeError, onArtifactReady, canvasTrackProps]);const clearHistoricalArtifactError = useCallback(() => {onHistoricalArtifactReady();setRuntimeError(threadId, null);diff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.tsindex d480913745b3..5cf055dba4de 100644--- a/products/platform_features/frontend/generated/api.schemas.ts+++ b/products/platform_features/frontend/generated/api.schemas.ts@@ -1094,6 +1094,7 @@ export type ActivityLogListParams = {* * `EventDefinition` - EventDefinition* * `PropertyDefinition` - PropertyDefinition* * `Notebook` - Notebook+ * * `Canvas` - Canvas* * `Endpoint` - Endpoint* * `EndpointVersion` - EndpointVersion* * `Dashboard` - Dashboard@@ -1188,6 +1189,7 @@ export const ActivityLogListScope = {EventDefinition: 'EventDefinition',PropertyDefinition: 'PropertyDefinition',Notebook: 'Notebook',+ Canvas: 'Canvas',Endpoint: 'Endpoint',EndpointVersion: 'EndpointVersion',Dashboard: 'Dashboard',@@ -1269,6 +1271,7 @@ export const ActivityLogListScope = {* * `EventDefinition` - EventDefinition* * `PropertyDefinition` - PropertyDefinition* * `Notebook` - Notebook+ * * `Canvas` - Canvas* * `Endpoint` - Endpoint* * `EndpointVersion` - EndpointVersion* * `Dashboard` - Dashboard@@ -1351,6 +1354,7 @@ export const ActivityLogListScopesItem = {EventDefinition: 'EventDefinition',PropertyDefinition: 'PropertyDefinition',Notebook: 'Notebook',+ Canvas: 'Canvas',Endpoint: 'Endpoint',EndpointVersion: 'EndpointVersion',Dashboard: 'Dashboard',diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex b96c55864c26..0f4f6ee4fa58 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -79710,6 +79710,7 @@ export namespace Schemas {* * `EventDefinition` - EventDefinition* * `PropertyDefinition` - PropertyDefinition* * `Notebook` - Notebook+ * * `Canvas` - Canvas* * `Endpoint` - Endpoint* * `EndpointVersion` - EndpointVersion* * `Dashboard` - Dashboard@@ -79805,6 +79806,7 @@ export namespace Schemas {EventDefinition: 'EventDefinition',PropertyDefinition: 'PropertyDefinition',Notebook: 'Notebook',+ Canvas: 'Canvas',Endpoint: 'Endpoint',EndpointVersion: 'EndpointVersion',Dashboard: 'Dashboard',@@ -79886,6 +79888,7 @@ export namespace Schemas {* * `EventDefinition` - EventDefinition* * `PropertyDefinition` - PropertyDefinition* * `Notebook` - Notebook+ * * `Canvas` - Canvas* * `Endpoint` - Endpoint* * `EndpointVersion` - EndpointVersion* * `Dashboard` - Dashboard@@ -79969,6 +79972,7 @@ export namespace Schemas {EventDefinition: 'EventDefinition',PropertyDefinition: 'PropertyDefinition',Notebook: 'Notebook',+ Canvas: 'Canvas',Endpoint: 'Endpoint',EndpointVersion: 'EndpointVersion',Dashboard: 'Dashboard',diff --git a/tach.toml b/tach.tomlindex c80ad4c5fe6e..5e7d995eb62f 100644--- a/tach.toml+++ b/tach.toml@@ -842,6 +842,16 @@ from = ["products.canvas",]+# The shared activity log delegates personal-canvas visibility to this narrow,+# product-owned boundary, mirroring how loops do it for tasks.+[[interfaces]]+expose = [+ "backend\\.activity_visibility.*",+]+from = [+ "products.canvas",+]+[[modules]]path = "products.tracing"depends_on = [