: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
chore(deployments): scaffold flag-gated deployments product (#58421)
Richard Solomoue47a706429f5
diff --git a/.semgrep/rules/idor-team-scoped-models.yaml b/.semgrep/rules/idor-team-scoped-models.yamlindex 3da653401470..4b5cb18df810 100644--- a/.semgrep/rules/idor-team-scoped-models.yaml+++ b/.semgrep/rules/idor-team-scoped-models.yaml@@ -91,6 +91,7 @@ rules:|DataWarehouseSavedQueryDraft|DataWarehouseSavedQueryFolder|DataWarehouseTable+ |Deployment|DesktopRecording|EarlyAccessFeature|EmailMessageMapping@@ -307,6 +308,7 @@ rules:|DataWarehouseSavedQueryDraft|DataWarehouseSavedQueryFolder|DataWarehouseTable+ |Deployment|DesktopRecording|EarlyAccessFeature|EmailMessageMappingdiff --git a/frontend/package.json b/frontend/package.jsonindex ca51d5ec4ced..4bfec0a4ef4b 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -78,6 +78,7 @@"@posthog/products-dashboards": "workspace:*","@posthog/products-data-modeling": "workspace:*","@posthog/products-data-warehouse": "workspace:*",+ "@posthog/products-deployments": "workspace:*","@posthog/products-early-access-features": "workspace:*","@posthog/products-endpoints": "workspace:*","@posthog/products-error-tracking": "workspace:*",diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 40d69ec97499..9a1e28c9a9a4 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -267,6 +267,7 @@ export const FEATURE_FLAGS = {DATA_MODELING_TAB: 'data-modeling-tab', // owner: #team-data-modelingDATA_WAREHOUSE_SCENE: 'data-warehouse-scene', // owner: #team-data-modelingDEFAULT_EVALUATION_ENVIRONMENTS: 'default-evaluation-environments', // owner: @dmarticus #team-feature-flags+ DEPLOYMENTS: 'deployments', // owner: @richardsolomouDROP_PERSON_LIST_ORDER_BY: 'drop-person-list-order-by', // owner: @arthurdedeus #team-customer-analyticsDWH_FREE_SYNCS: 'dwh-free-syncs', // owner: @Gilbert09 #team-warehouse-sourcesDWH_JOIN_TABLE_PREVIEW: 'dwh-join-table-preview', // owner: @arthurdedeus #team-customer-analyticsdiff --git a/frontend/src/lib/scopes.tsx b/frontend/src/lib/scopes.tsxindex b6623bb604f7..fed61b93f90d 100644--- a/frontend/src/lib/scopes.tsx+++ b/frontend/src/lib/scopes.tsx@@ -29,6 +29,7 @@ export const API_SCOPES: APIScope[] = [{ key: 'dashboard', objectName: 'Dashboard', objectPlural: 'dashboards' },{ key: 'dashboard_template', objectName: 'Dashboard template', objectPlural: 'dashboard templates' },{ key: 'dataset', objectName: 'Dataset', objectPlural: 'datasets' },+ { key: 'deployment', objectName: 'Deployment', objectPlural: 'deployments' },{ key: 'desktop_recording', objectName: 'Desktop recording', objectPlural: 'desktop recordings' },{ key: 'early_access_feature', objectName: 'Early access feature', objectPlural: 'early access features' },{ key: 'element', objectName: 'Element', objectPlural: 'elements' },diff --git a/frontend/src/products.json b/frontend/src/products.jsonindex 76a3e1436a7e..f4ce046aa386 100644--- a/frontend/src/products.json+++ b/frontend/src/products.json@@ -42,6 +42,7 @@"type": null,"intents": ["data_warehouse", "data_warehouse_saved_queries"]},+ { "path": "Deployments", "category": "Tools", "iconType": null, "type": "live", "intents": ["deployments"] },{"path": "Early access features","category": "Features",diff --git a/frontend/src/products.tsx b/frontend/src/products.tsxindex 067bb57d84b0..7a2b00993231 100644--- a/frontend/src/products.tsx+++ b/frontend/src/products.tsx@@ -70,6 +70,8 @@ export const productScenes: Record<string, () => Promise<any>> = {DataWarehouseSource: () => import('../../products/data_warehouse/frontend/scenes/SourceScene/SourceScene'),DataWarehouseSourceNew: () => import('../../products/data_warehouse/frontend/scenes/NewSourceScene/NewSourceScene'),DataWarehouseSourceSchema: () => import('../../products/data_warehouse/frontend/scenes/SchemaScene/SchemaScene'),+ Deployments: () => import('../../products/deployments/frontend/Deployments'),+ Deployment: () => import('../../products/deployments/frontend/Deployment'),EarlyAccessFeatures: () => import('../../products/early_access_features/frontend/EarlyAccessFeatures'),EarlyAccessFeature: () => import('../../products/early_access_features/frontend/EarlyAccessFeature'),EndpointsScene: () => import('../../products/endpoints/frontend/EndpointsScene'),@@ -169,6 +171,8 @@ export const productRoutes: Record<string, [string, string]> = {],'/data-management/sources/:id/:tab': ['DataWarehouseSource', 'dataWarehouseSource'],'/data-warehouse/new-source': ['DataWarehouseSourceNew', 'dataWarehouseSourceNew'],+ '/deployments': ['Deployments', 'deployments'],+ '/deployments/:id': ['Deployment', 'deployment'],'/early_access_features': ['EarlyAccessFeatures', 'earlyAccessFeatures'],'/early_access_features/:id': ['EarlyAccessFeature', 'earlyAccessFeature'],'/endpoints': ['EndpointsScene', 'endpoints'],@@ -370,6 +374,13 @@ export const productConfiguration: Record<string, any> = {DataWarehouseSource: { projectBased: true, name: 'Data warehouse source' },DataWarehouseSourceNew: { projectBased: true, name: 'New data warehouse source' },DataWarehouseSourceSchema: { projectBased: true, name: 'Data warehouse schema' },+ Deployments: {+ projectBased: true,+ name: 'Deployments',+ iconType: 'live',+ description: 'Build and ship your project site straight from PostHog.',+ },+ Deployment: { projectBased: true, name: 'Deployment' },EarlyAccessFeatures: {name: 'Early access features',projectBased: true,@@ -696,6 +707,8 @@ export const productUrls = {const queryString = params.toString()return `/data-warehouse/new-source${queryString ? `?${queryString}` : ''}`},+ deployments: (): string => '/deployments',+ deployment: (id: string): string => `/deployments/${id}`,earlyAccessFeatures: (): string => '/early_access_features',earlyAccessFeature: (id: string): string => `/early_access_features/${id}`,endpoints: (): string => '/endpoints',@@ -1414,6 +1427,19 @@ export const getTreeItemsProducts = (): FileSystemImport[] => ['LLMAnalyticsCluster',],},+ {+ path: 'Deployments',+ intents: [ProductKey.DEPLOYMENTS],+ category: ProductItemCategory.TOOLS,+ href: urls.deployments(),+ type: 'live',+ iconType: 'live' as FileSystemIconType,+ iconColor: ['var(--color-text-3000)'] as FileSystemIconColor,+ sceneKey: 'Deployments',+ sceneKeys: ['Deployments', 'Deployment'],+ flag: FEATURE_FLAGS.DEPLOYMENTS,+ tags: ['alpha'],+ },{path: 'Early access features',intents: [ProductKey.EARLY_ACCESS_FEATURES],diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex f821ad205237..cd5146a7d42a 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -27158,6 +27158,7 @@"customer_analytics","data_warehouse","data_warehouse_saved_queries",+ "deployments","early_access_features","endpoints","error_tracking",diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 85ed574bf0fe..996cc88becb3 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -6277,6 +6277,7 @@ export enum ProductKey {CUSTOMER_ANALYTICS = 'customer_analytics',DATA_WAREHOUSE = 'data_warehouse',DATA_WAREHOUSE_SAVED_QUERY = 'data_warehouse_saved_queries',+ DEPLOYMENTS = 'deployments',EARLY_ACCESS_FEATURES = 'early_access_features',ENDPOINTS = 'endpoints',ERROR_TRACKING = 'error_tracking',diff --git a/frontend/src/scenes/sceneTypes.ts b/frontend/src/scenes/sceneTypes.tsindex 0c836d64fecc..173678e3e895 100644--- a/frontend/src/scenes/sceneTypes.ts+++ b/frontend/src/scenes/sceneTypes.ts@@ -62,6 +62,8 @@ export enum Scene {Subscription = 'Subscription',ExperimentsSharedMetric = 'ExperimentsSharedMetric',ExperimentsSharedMetrics = 'ExperimentsSharedMetrics',+ Deployment = 'Deployment',+ Deployments = 'Deployments',ExploreEvents = 'ExploreEvents',ExploreSessions = 'ExploreSessions',FeatureFlag = 'FeatureFlag',diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 2185caed1d1c..e0b8c238f7ea 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -5293,6 +5293,7 @@ export type APIScopeObject =| 'dashboard'| 'dashboard_template'| 'dataset'+ | 'deployment'| 'desktop_recording'| 'early_access_feature'| 'element'diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex d98e27863a97..f43b1859ce81 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -622,6 +622,9 @@ importers:'@posthog/products-data-warehouse':specifier: workspace:*version: link:../products/data_warehouse+ '@posthog/products-deployments':+ specifier: workspace:*+ version: link:../products/deployments'@posthog/products-early-access-features':specifier: workspace:*version: link:../products/early_access_features@@ -2331,6 +2334,34 @@ importers:specifier: 18.3.1version: 18.3.1+ products/deployments:+ dependencies:+ '@posthog/icons':+ specifier: '*'+ '@types/react':+ specifier: 18.3.27+ version: 18.3.27+ kea:+ specifier: 'catalog:'+ version: 4.0.0-pre.5([email protected])+ kea-loaders:+ specifier: 'catalog:'+ version: 3.1.1([email protected]([email protected]))+ kea-router:+ specifier: 'catalog:'+ version: 3.4.1([email protected]([email protected]))+ posthog-js:+ specifier: 'catalog:'+ version: 1.373.4+ react:+ specifier: 18.3.1+ version: 18.3.1+ devDependencies:+ kea-test-utils:+ specifier: 'catalog:'+ version: 0.2.4([email protected]([email protected]))+products/desktop_recordings: {}products/early_access_features:diff --git a/posthog/api/__init__.py b/posthog/api/__init__.pyindex 71571097a9dc..44fd106f49da 100644--- a/posthog/api/__init__.py+++ b/posthog/api/__init__.py@@ -29,6 +29,7 @@ import products.tasks.backend.api as tasksimport products.endpoints.backend.api as endpointsimport products.signals.backend.views as signalsimport products.tasks.backend.seat_api as seats+import products.deployments.backend.api as deploymentsimport products.conversations.backend.api as conversationsimport products.live_debugger.backend.api as live_debuggerimport products.web_analytics.backend.api as web_analytics_api@@ -312,6 +313,12 @@ project_features_router = projects_router.register("project_early_access_feature",["project_id"],)+projects_router.register(+ r"deployments",+ deployments.DeploymentViewSet,+ "project_deployments",+ ["project_id"],+)# Tasks endpointsproject_tasks_router = projects_router.register(r"tasks", tasks.TaskViewSet, "project_tasks", ["team_id"])diff --git a/posthog/schema.py b/posthog/schema.pyindex 0648b3aa6e22..7450aff94c05 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -3791,6 +3791,7 @@ class ProductKey(StrEnum):CUSTOMER_ANALYTICS = "customer_analytics"DATA_WAREHOUSE = "data_warehouse"DATA_WAREHOUSE_SAVED_QUERIES = "data_warehouse_saved_queries"+ DEPLOYMENTS = "deployments"EARLY_ACCESS_FEATURES = "early_access_features"ENDPOINTS = "endpoints"ERROR_TRACKING = "error_tracking"diff --git a/posthog/scopes.py b/posthog/scopes.pyindex 9a543214622e..a5cd0df57d26 100644--- a/posthog/scopes.py+++ b/posthog/scopes.py@@ -34,6 +34,7 @@ APIScopeObject = Literal["event_filter","dashboard_template","dataset",+ "deployment","desktop_recording","early_access_feature","endpoint",diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 682f5b0313ba..dbed9af9806d 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -74,6 +74,7 @@ PRODUCTS_APPS = ["products.access_control.backend.apps.AccessControlConfig","products.warehouse_sources_queue.backend.apps.WarehouseSourcesQueueConfig","products.business_knowledge.backend.apps.BusinessKnowledgeConfig",+ "products.deployments.backend.apps.DeploymentsConfig",]INSTALLED_APPS = [diff --git a/products/deployments/__init__.py b/products/deployments/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/deployments/backend/__init__.py b/products/deployments/backend/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/deployments/backend/access.py b/products/deployments/backend/access.pynew file mode 100644index 000000000000..6b413f952bd5--- /dev/null+++ b/products/deployments/backend/access.py@@ -0,0 +1,31 @@+"""Feature-flag gate for the Deployments product.++Access is gated on the `deployments` feature flag. Rollout (e.g. limiting to+specific teams or organizations) is configured on the flag itself in the+PostHog admin — code only asks 'is this enabled for this user / team?' and+returns the answer.+"""++from django.contrib.auth.models import AbstractBaseUser, AnonymousUser++import posthoganalytics+++def has_deployments_access(user: AbstractBaseUser | AnonymousUser | None, *, team_id: int | None = None) -> bool:+ # Accept the union DRF gives us on `request.user` (authenticated User or AnonymousUser).+ # Bail on anything that can't carry a distinct_id — the flag check below needs one.+ if not user or not user.is_authenticated:+ return False+ distinct_id = getattr(user, "distinct_id", None)+ if not distinct_id:+ return False++ kwargs: dict = {+ "only_evaluate_locally": False,+ "send_feature_flag_events": False,+ }+ if team_id is not None:+ kwargs["groups"] = {"project": str(team_id)}+ kwargs["group_properties"] = {"project": {"id": str(team_id)}}++ return bool(posthoganalytics.feature_enabled("deployments", distinct_id, **kwargs))diff --git a/products/deployments/backend/api/__init__.py b/products/deployments/backend/api/__init__.pynew file mode 100644index 000000000000..3ba09ed6dbaa--- /dev/null+++ b/products/deployments/backend/api/__init__.py@@ -0,0 +1,3 @@+from .deployments import DeploymentViewSet++__all__ = ["DeploymentViewSet"]diff --git a/products/deployments/backend/api/deployments.py b/products/deployments/backend/api/deployments.pynew file mode 100644index 000000000000..323c6d6df6c9--- /dev/null+++ b/products/deployments/backend/api/deployments.py@@ -0,0 +1,254 @@+"""DRF wiring for the Deployments product.++Scaffold only. The serializer surfaces every model field with `help_text`+so generated TypeScript types and MCP tools have real descriptions, but+computed fields (`is_current`, `duration_seconds`) return hardcoded+placeholders. The viewset registers `list`, `retrieve`, and the+501-stubbed actions (`redeploy`, `rollback`, `refresh_preview`).+"""++from __future__ import annotations++from typing import Any++from drf_spectacular.utils import OpenApiResponse, extend_schema, extend_schema_field+from rest_framework import serializers, status, viewsets+from rest_framework.decorators import action+from rest_framework.permissions import BasePermission+from rest_framework.request import Request+from rest_framework.response import Response+from rest_framework.views import APIView++from posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin++from ..access import has_deployments_access+from ..models import Deployment+++class DeploymentsAccessPermission(BasePermission):+ """Gate the whole product behind the `deployments` feature flag.++ Returns 403 instead of 404 because we already have a flag-driven+ sidebar entry — there's no point pretending the URL doesn't exist+ once a request has reached this viewset.+ """++ message = "Deployments is not enabled for this team."++ def has_permission(self, request: Request, view: APIView) -> bool:+ team_id = getattr(view, "team_id", None)+ return has_deployments_access(request.user, team_id=team_id)+++class DeploymentSerializer(serializers.ModelSerializer):+ id = serializers.UUIDField(read_only=True, help_text="Unique identifier for the deployment.")+ status = serializers.ChoiceField(+ choices=Deployment.Status.choices,+ help_text=(+ "Current pipeline stage for the deployment. Valid values: "+ "queued, initializing, building, ready, error, cancelled."+ ),+ )+ started_at = serializers.DateTimeField(+ allow_null=True,+ required=False,+ help_text="Timestamp when the pipeline started building. Null while still queued.",+ )+ finished_at = serializers.DateTimeField(+ allow_null=True,+ required=False,+ help_text="Timestamp when the pipeline finished (regardless of outcome). Null while still running.",+ )+ created_at = serializers.DateTimeField(+ read_only=True,+ help_text="Timestamp when the deployment row was created.",+ )++ commit_sha = serializers.CharField(+ allow_blank=True,+ required=False,+ max_length=64,+ help_text="Git commit SHA the deployment was built from. Empty for non-git triggers.",+ )+ commit_message = serializers.CharField(+ allow_blank=True,+ required=False,+ help_text="Commit message associated with the commit SHA.",+ )+ commit_author_name = serializers.CharField(+ allow_blank=True,+ required=False,+ max_length=255,+ help_text="Display name of the commit author.",+ )+ commit_author_email = serializers.CharField(+ allow_blank=True,+ required=False,+ max_length=255,+ help_text="Email address of the commit author.",+ )++ repo_url = serializers.URLField(+ allow_blank=True,+ required=False,+ max_length=1024,+ help_text="HTTPS URL of the source repository this deployment came from.",+ )+ branch = serializers.CharField(+ allow_blank=True,+ required=False,+ max_length=255,+ help_text="Source branch the deployment was built from.",+ )++ deployment_url = serializers.URLField(+ allow_blank=True,+ required=False,+ max_length=1024,+ help_text="Public URL where the built site is served once the deployment is ready.",+ )+ preview_image_url = serializers.URLField(+ allow_blank=True,+ required=False,+ max_length=1024,+ help_text="URL of a screenshot capture of the deployed site, used in the list view.",+ )++ triggered_by_deployment: serializers.PrimaryKeyRelatedField = serializers.PrimaryKeyRelatedField( # ty: ignore[invalid-assignment]+ read_only=True,+ allow_null=True,+ help_text="The deployment this one was triggered from (e.g. for rollbacks/redeploys).",+ )+ trigger_kind = serializers.ChoiceField(+ choices=Deployment.TriggerKind.choices,+ help_text="What caused this deployment to start. One of: git, redeploy, rollback, seed.",+ )++ is_current = serializers.SerializerMethodField(+ help_text="Whether this deployment is the team's currently-serving production deployment.",+ )+ duration_seconds = serializers.SerializerMethodField(+ help_text="Build duration in seconds (finished_at - started_at). 0 while still running.",+ )++ class Meta:+ model = Deployment+ fields = [+ "id",+ "status",+ "started_at",+ "finished_at",+ "created_at",+ "commit_sha",+ "commit_message",+ "commit_author_name",+ "commit_author_email",+ "repo_url",+ "branch",+ "deployment_url",+ "preview_image_url",+ "triggered_by_deployment",+ "trigger_kind",+ "is_current",+ "duration_seconds",+ ]+ # SerializerMethodField is always read-only in DRF, so listing+ # is_current / duration_seconds here would be redundant.+ read_only_fields = ["id", "created_at", "triggered_by_deployment"]++ # TODO(deployments-v1): replace with a real `Subquery`/annotation that+ # marks the most recent `READY` deployment per team as current.+ @extend_schema_field(serializers.BooleanField())+ def get_is_current(self, obj: Deployment) -> bool:+ return False++ # TODO(deployments-v1): replace with `(finished_at - started_at).total_seconds()`+ # once the mock pipeline starts writing timestamps.+ @extend_schema_field(serializers.IntegerField())+ def get_duration_seconds(self, obj: Deployment) -> int:+ return 0+++class DeploymentActionResponseSerializer(serializers.Serializer):+ """Response shape for the redeploy/rollback/refresh-preview stubs."""++ detail = serializers.CharField(help_text="Human-readable explanation of the stub response.")+++@extend_schema(tags=["deployments"])+class DeploymentViewSet(+ TeamAndOrgViewSetMixin,+ AccessControlViewSetMixin,+ viewsets.ReadOnlyModelViewSet,+):+ """Read-only viewset for the Deployments product.++ `list` and `retrieve` are wired against the model queryset. The+ `@action` stubs (`redeploy`, `rollback`, `refresh_preview`) intentionally+ return 501 — they exist so OpenAPI / MCP can discover the surface area+ while behavior lands in follow-up commits.+ """++ scope_object = "deployment"+ # The TeamAndOrgViewSetMixin appends class-level permission_classes to its+ # mandatory set (IsAuthenticated + APIScopePermission + AccessControlPermission+ # + TeamMemberAccessPermission), so we get the feature-flag gate on top of+ # all the standard checks without overriding get_permissions (which the mixin+ # protects via __init_subclass__).+ permission_classes = [DeploymentsAccessPermission]+ serializer_class = DeploymentSerializer+ # Use `all_teams` (the unscoped sibling manager) at class-definition+ # time — `objects` is fail-closed and would raise without a team+ # context. `safely_get_queryset` re-applies the team filter explicitly.+ queryset = Deployment.all_teams.all()++ def _should_skip_parents_filter(self) -> bool:+ # The router's default `parents_query_dict` filter assumes a `team` FK+ # and rewrites `project_id` to `team__project_id` — but `Deployment`+ # stores `team_id` as a plain `BigIntegerField`. `safely_get_queryset`+ # below applies the team scope directly using `self.team_id`.+ return True++ def safely_get_queryset(self, queryset: Any) -> Any:+ # TODO(deployments-v1): wire filters (status, author, search) once+ # `DeploymentsFilters` is implemented on the frontend.+ return queryset.filter(team_id=self.team_id)++ @extend_schema(+ request=None,+ responses={status.HTTP_501_NOT_IMPLEMENTED: OpenApiResponse(response=DeploymentActionResponseSerializer)},+ )+ @action(detail=True, methods=["post"])+ def redeploy(self, request: Request, **kwargs: Any) -> Response:+ # TODO(deployments-v1): enqueue a redeploy by cloning this deployment's commit_sha.+ return Response(+ DeploymentActionResponseSerializer({"detail": "Redeploy is not implemented yet."}).data,+ status=status.HTTP_501_NOT_IMPLEMENTED,+ )++ @extend_schema(+ request=None,+ responses={status.HTTP_501_NOT_IMPLEMENTED: OpenApiResponse(response=DeploymentActionResponseSerializer)},+ )+ @action(detail=True, methods=["post"])+ def rollback(self, request: Request, **kwargs: Any) -> Response:+ # TODO(deployments-v1): make this deployment the currently-serving one,+ # creating a new `rollback`-trigger deployment that points at it.+ return Response(+ DeploymentActionResponseSerializer({"detail": "Rollback is not implemented yet."}).data,+ status=status.HTTP_501_NOT_IMPLEMENTED,+ )++ @extend_schema(+ request=None,+ responses={status.HTTP_501_NOT_IMPLEMENTED: OpenApiResponse(response=DeploymentActionResponseSerializer)},+ )+ @action(detail=True, methods=["post"], url_path="refresh-preview")+ def refresh_preview(self, request: Request, **kwargs: Any) -> Response:+ # TODO(deployments-v1): re-capture `preview_image_url` via the+ # microlink-backed `preview_capture` service.+ return Response(+ DeploymentActionResponseSerializer({"detail": "Refresh preview is not implemented yet."}).data,+ status=status.HTTP_501_NOT_IMPLEMENTED,+ )diff --git a/products/deployments/backend/apps.py b/products/deployments/backend/apps.pynew file mode 100644index 000000000000..2b21047aea3a--- /dev/null+++ b/products/deployments/backend/apps.py@@ -0,0 +1,7 @@+from django.apps import AppConfig+++class DeploymentsConfig(AppConfig):+ default_auto_field = "django.db.models.BigAutoField"+ name = "products.deployments.backend"+ label = "deployments"diff --git a/products/deployments/backend/management/__init__.py b/products/deployments/backend/management/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/deployments/backend/management/commands/__init__.py b/products/deployments/backend/management/commands/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/deployments/backend/management/commands/seed_deployments.py b/products/deployments/backend/management/commands/seed_deployments.pynew file mode 100644index 000000000000..56110f92b79f--- /dev/null+++ b/products/deployments/backend/management/commands/seed_deployments.py@@ -0,0 +1,17 @@+"""`manage.py seed_deployments` — placeholder for realistic dev seeds."""++from __future__ import annotations++from typing import Any++from django.core.management.base import BaseCommand+++class Command(BaseCommand):+ help = "Seed mock deployments for local development. Not yet implemented."++ def handle(self, *args: Any, **options: Any) -> None:+ # TODO(deployments-v1): generate a realistic stream of deployments+ # (varied statuses, authors, branches) for the team passed via+ # --team-id, so the list scene has something to show locally.+ self.stdout.write("TODO: seed_deployments is not implemented yet.")diff --git a/products/deployments/backend/migrations/0001_initial.py b/products/deployments/backend/migrations/0001_initial.pynew file mode 100644index 000000000000..09ab2880ff31--- /dev/null+++ b/products/deployments/backend/migrations/0001_initial.py@@ -0,0 +1,90 @@+# Generated by Django 4.2.29 — initial scaffold for the Deployments product.++import django.db.models.deletion+from django.db import migrations, models++import posthog.models.utils+++class Migration(migrations.Migration):+ initial = True++ dependencies = []++ operations = [+ migrations.CreateModel(+ name="Deployment",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("team_id", models.BigIntegerField(db_index=True)),+ (+ "status",+ models.CharField(+ choices=[+ ("queued", "Queued"),+ ("initializing", "Initializing"),+ ("building", "Building"),+ ("ready", "Ready"),+ ("error", "Error"),+ ("cancelled", "Cancelled"),+ ],+ db_index=True,+ default="queued",+ max_length=32,+ ),+ ),+ ("started_at", models.DateTimeField(blank=True, null=True)),+ ("finished_at", models.DateTimeField(blank=True, null=True)),+ ("created_at", models.DateTimeField(auto_now_add=True, db_index=True)),+ ("commit_sha", models.CharField(blank=True, default="", max_length=64)),+ ("commit_message", models.TextField(blank=True, default="")),+ ("commit_author_name", models.CharField(blank=True, default="", max_length=255)),+ ("commit_author_email", models.CharField(blank=True, default="", max_length=255)),+ ("repo_url", models.URLField(blank=True, default="", max_length=1024)),+ ("branch", models.CharField(blank=True, default="", max_length=255)),+ ("deployment_url", models.URLField(blank=True, default="", max_length=1024)),+ ("preview_image_url", models.URLField(blank=True, default="", max_length=1024)),+ (+ "trigger_kind",+ models.CharField(+ choices=[+ ("git", "Git"),+ ("redeploy", "Redeploy"),+ ("rollback", "Rollback"),+ ("seed", "Seed"),+ ],+ default="git",+ max_length=16,+ ),+ ),+ (+ "triggered_by_deployment",+ models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="+",+ to="deployments.deployment",+ ),+ ),+ ],+ options={+ "ordering": ("-created_at",),+ },+ ),+ migrations.AddIndex(+ model_name="deployment",+ index=models.Index(+ fields=["team_id", "-created_at"],+ name="deploy_team_created_idx",+ ),+ ),+ ]diff --git a/products/deployments/backend/migrations/__init__.py b/products/deployments/backend/migrations/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/deployments/backend/migrations/max_migration.txt b/products/deployments/backend/migrations/max_migration.txtnew file mode 100644index 000000000000..cbab66dde92a--- /dev/null+++ b/products/deployments/backend/migrations/max_migration.txt@@ -0,0 +1 @@+0001_initialdiff --git a/products/deployments/backend/models.py b/products/deployments/backend/models.pynew file mode 100644index 000000000000..888300a3e001--- /dev/null+++ b/products/deployments/backend/models.py@@ -0,0 +1,82 @@+"""Django models for the Deployments product.++Scaffold only — fields and choices land here so other commits on+`feat/deployments` can build behavior on top. Business logic, signals,+and activity describers will be filled in later.+"""++from __future__ import annotations++from django.db import models++from posthog.models.activity_logging.model_activity import ModelActivityMixin+from posthog.models.scoping.product_mixin import ProductTeamModel+from posthog.models.utils import uuid7+++class Deployment(ModelActivityMixin, ProductTeamModel):+ """A single deployment of a project's site.++ `team_id` is inherited from `ProductTeamModel` as a plain+ `BigIntegerField` — no cross-DB FK to `Team`. All reads go through+ the fail-closed `TeamScopedManager`.+ """++ class Status(models.TextChoices):+ QUEUED = "queued", "Queued"+ INITIALIZING = "initializing", "Initializing"+ BUILDING = "building", "Building"+ READY = "ready", "Ready"+ ERROR = "error", "Error"+ CANCELLED = "cancelled", "Cancelled"++ class TriggerKind(models.TextChoices):+ GIT = "git", "Git"+ REDEPLOY = "redeploy", "Redeploy"+ ROLLBACK = "rollback", "Rollback"+ SEED = "seed", "Seed"++ id = models.UUIDField(primary_key=True, default=uuid7, editable=False)++ status = models.CharField(+ max_length=32,+ choices=Status.choices,+ default=Status.QUEUED,+ db_index=True,+ )+ started_at = models.DateTimeField(null=True, blank=True)+ finished_at = models.DateTimeField(null=True, blank=True)+ created_at = models.DateTimeField(auto_now_add=True, db_index=True)++ commit_sha = models.CharField(max_length=64, blank=True, default="")+ commit_message = models.TextField(blank=True, default="")+ commit_author_name = models.CharField(max_length=255, blank=True, default="")+ commit_author_email = models.CharField(max_length=255, blank=True, default="")++ repo_url = models.URLField(max_length=1024, blank=True, default="")+ branch = models.CharField(max_length=255, blank=True, default="")++ deployment_url = models.URLField(max_length=1024, blank=True, default="")+ preview_image_url = models.URLField(max_length=1024, blank=True, default="")++ triggered_by_deployment = models.ForeignKey(+ "self",+ null=True,+ blank=True,+ on_delete=models.SET_NULL,+ related_name="+",+ )+ trigger_kind = models.CharField(+ max_length=16,+ choices=TriggerKind.choices,+ default=TriggerKind.GIT,+ )++ class Meta:+ ordering = ("-created_at",)+ indexes = [+ models.Index(fields=("team_id", "-created_at"), name="deploy_team_created_idx"),+ ]++ def __str__(self) -> str:+ return f"Deployment {self.id} ({self.status})"diff --git a/products/deployments/backend/services/__init__.py b/products/deployments/backend/services/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/deployments/backend/services/mock_pipeline.py b/products/deployments/backend/services/mock_pipeline.pynew file mode 100644index 000000000000..c5f9a900e157--- /dev/null+++ b/products/deployments/backend/services/mock_pipeline.py@@ -0,0 +1,6 @@+"""Mock build pipeline for the Deployments product.++# TODO(deployments-v1): walk a deployment through Queued -> Initializing+# -> Building -> Ready, writing `started_at` / `finished_at` along the way.+# Will be exposed as a Celery task once `posthog/celery.py` is wired.+"""diff --git a/products/deployments/backend/services/preview_capture.py b/products/deployments/backend/services/preview_capture.pynew file mode 100644index 000000000000..12167df0d7d1--- /dev/null+++ b/products/deployments/backend/services/preview_capture.py@@ -0,0 +1,5 @@+"""Preview screenshot capture for the Deployments product.++# TODO(deployments-v1): wire up microlink-backed screenshot capture and+# persistence of `preview_image_url` on the `Deployment` model.+"""diff --git a/products/deployments/backend/test/__init__.py b/products/deployments/backend/test/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/deployments/backend/test/test_deployments_api.py b/products/deployments/backend/test/test_deployments_api.pynew file mode 100644index 000000000000..05c2450138aa--- /dev/null+++ b/products/deployments/backend/test/test_deployments_api.py@@ -0,0 +1,41 @@+from posthog.test.base import APIBaseTest+from unittest.mock import patch++from parameterized import parameterized+from rest_framework import status++from posthog.models.utils import uuid7+++class TestDeploymentsAPI(APIBaseTest):+ @parameterized.expand(+ [+ ("flag on returns empty list", True, status.HTTP_200_OK),+ ("flag off returns 403", False, status.HTTP_403_FORBIDDEN),+ ]+ )+ def test_list_respects_feature_flag(self, _name: str, flag_enabled: bool, expected_status: int) -> None:+ with patch(+ "products.deployments.backend.access.posthoganalytics.feature_enabled",+ return_value=flag_enabled,+ ):+ response = self.client.get(f"/api/projects/{self.team.id}/deployments/")++ self.assertEqual(response.status_code, expected_status)+ if expected_status == status.HTTP_200_OK:+ self.assertEqual(response.json()["results"], [])++ @parameterized.expand(+ [+ ("redeploy",),+ ("rollback",),+ ("refresh-preview",),+ ]+ )+ @patch("products.deployments.backend.access.posthoganalytics.feature_enabled", return_value=True)+ def test_stub_action_returns_501_when_flag_on(self, action: str, _mock_flag: object) -> None:+ # The stubs never call get_object, so the deployment id only has to be a+ # syntactically valid UUID — no row needs to exist for the URL to route.+ response = self.client.post(f"/api/projects/{self.team.id}/deployments/{uuid7()}/{action}/")++ self.assertEqual(response.status_code, status.HTTP_501_NOT_IMPLEMENTED)diff --git a/products/deployments/frontend/Deployment.tsx b/products/deployments/frontend/Deployment.tsxnew file mode 100644index 000000000000..50eced0fbaed--- /dev/null+++ b/products/deployments/frontend/Deployment.tsx@@ -0,0 +1,25 @@+import { Link } from '@posthog/lemon-ui'++import { SceneExport } from 'scenes/sceneTypes'+import { urls } from 'scenes/urls'++import { SceneContent } from '~/layout/scenes/components/SceneContent'++export const scene: SceneExport = {+ component: Deployment,+}++export function Deployment(): JSX.Element {+ return (+ <SceneContent>+ <div className="flex flex-col gap-2">+ {/* TODO(deployments-v1): load the deployment by id (URL param) and render its details. */}+ <h2>Deployment</h2>+ <p>Deployment details are not implemented yet.</p>+ <Link to={urls.deployments()}>Back to deployments</Link>+ </div>+ </SceneContent>+ )+}++export default Deploymentdiff --git a/products/deployments/frontend/Deployments.tsx b/products/deployments/frontend/Deployments.tsxnew file mode 100644index 000000000000..98f397b7449e--- /dev/null+++ b/products/deployments/frontend/Deployments.tsx@@ -0,0 +1,49 @@+import { BindLogic } from 'kea'++import { ProductIntroduction } from 'lib/components/ProductIntroduction/ProductIntroduction'+import { sceneConfigurations } from 'scenes/scenes'+import { Scene, SceneExport } from 'scenes/sceneTypes'++import { SceneContent } from '~/layout/scenes/components/SceneContent'+import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'+import { ProductKey } from '~/queries/schema/schema-general'++import { CurrentDeploymentCard } from './components/CurrentDeploymentCard'+import { DeploymentsFilters } from './components/DeploymentsFilters'+import { deploymentsLogic } from './deploymentsLogic'++export const scene: SceneExport = {+ component: Deployments,+ logic: deploymentsLogic,+ productKey: ProductKey.DEPLOYMENTS,+}++export function Deployments({ tabId }: { tabId?: string } = {}): JSX.Element {+ return (+ <BindLogic logic={deploymentsLogic} props={{ tabId: tabId ?? '' }}>+ <SceneContent>+ <SceneTitleSection+ name={sceneConfigurations[Scene.Deployments].name}+ description={sceneConfigurations[Scene.Deployments].description}+ resourceType={{+ type: sceneConfigurations[Scene.Deployments].iconType || 'live',+ }}+ />+ {/* TODO(deployments-v1): render <CurrentDeploymentCard/> with the team's currently-serving deployment. */}+ <CurrentDeploymentCard />+ {/* TODO(deployments-v1): render <DeploymentsFilters/> with status / author / search controls. */}+ <DeploymentsFilters />+ <ProductIntroduction+ productName="Deployments"+ productKey={ProductKey.DEPLOYMENTS}+ thingName="deployment"+ description="Build and ship your project site straight from PostHog. Each push creates a deployment with its own preview URL."+ isEmpty+ />+ {/* TODO(deployments-v1): replace ProductIntroduction with a LemonTable of deployments. */}+ </SceneContent>+ </BindLogic>+ )+}++export default Deploymentsdiff --git a/products/deployments/frontend/components/CurrentDeploymentCard.tsx b/products/deployments/frontend/components/CurrentDeploymentCard.tsxnew file mode 100644index 000000000000..7b001ed7a753--- /dev/null+++ b/products/deployments/frontend/components/CurrentDeploymentCard.tsx@@ -0,0 +1,7 @@+// TODO(deployments-v1): render the team's currently-serving deployment with+// commit metadata, preview image, status tag, and "View live" / "View source" actions.+export function CurrentDeploymentCard(): null {+ return null+}++export default CurrentDeploymentCarddiff --git a/products/deployments/frontend/components/DeploymentStatusTag.tsx b/products/deployments/frontend/components/DeploymentStatusTag.tsxnew file mode 100644index 000000000000..6386b0c63d6a--- /dev/null+++ b/products/deployments/frontend/components/DeploymentStatusTag.tsx@@ -0,0 +1,7 @@+// TODO(deployments-v1): render a coloured LemonTag for each Deployment.Status+// (queued, initializing, building, ready, error, cancelled).+export function DeploymentStatusTag(): null {+ return null+}++export default DeploymentStatusTagdiff --git a/products/deployments/frontend/components/DeploymentsFilters.tsx b/products/deployments/frontend/components/DeploymentsFilters.tsxnew file mode 100644index 000000000000..cccba362e995--- /dev/null+++ b/products/deployments/frontend/components/DeploymentsFilters.tsx@@ -0,0 +1,7 @@+// TODO(deployments-v1): render status / author / search filter inputs and+// wire them through to `deploymentsLogic.setFilters`.+export function DeploymentsFilters(): null {+ return null+}++export default DeploymentsFiltersdiff --git a/products/deployments/frontend/deploymentsLogic.ts b/products/deployments/frontend/deploymentsLogic.tsnew file mode 100644index 000000000000..eaef56746eb9--- /dev/null+++ b/products/deployments/frontend/deploymentsLogic.ts@@ -0,0 +1,71 @@+import { actions, afterMount, kea, key, path, props, reducers } from 'kea'+import { loaders } from 'kea-loaders'+import { actionToUrl, urlToAction } from 'kea-router'++import { teamLogic } from 'scenes/teamLogic'+import { urls } from 'scenes/urls'++import type { deploymentsLogicType } from './deploymentsLogicType'+import { deploymentsList } from './generated/api'+import type { DeploymentApi } from './generated/api.schemas'++export interface DeploymentsFilters {+ status: string | null+ author: string | null+ search: string+}++export const DEFAULT_DEPLOYMENT_FILTERS: DeploymentsFilters = {+ status: null,+ author: null,+ search: '',+}++export interface DeploymentsLogicProps {+ tabId: string+}++export const deploymentsLogic = kea<deploymentsLogicType>([+ path(['products', 'deployments', 'frontend', 'deploymentsLogic']),+ props({} as DeploymentsLogicProps),+ key((props) => props.tabId),+ actions({+ // TODO(deployments-v1): wire setFilters once <DeploymentsFilters/> exists.+ setFilters: (filters: Partial<DeploymentsFilters>) => ({ filters }),+ }),+ loaders(() => ({+ deployments: [+ [] as DeploymentApi[],+ {+ loadDeployments: async () => {+ const projectId = teamLogic.values.currentTeamId+ if (!projectId) {+ return []+ }+ const response = await deploymentsList(String(projectId))+ return response.results || []+ },+ },+ ],+ })),+ reducers({+ filters: [+ DEFAULT_DEPLOYMENT_FILTERS,+ {+ setFilters: (state, { filters }) => ({ ...state, ...filters }),+ },+ ],+ }),+ afterMount(({ actions }) => {+ actions.loadDeployments()+ }),+ // TODO(deployments-v1): switch to tabAwareUrlToAction once filters live in the URL.+ urlToAction(() => ({+ [urls.deployments()]: () => {+ // placeholder — nothing to read from the URL yet.+ },+ })),+ actionToUrl(() => ({+ // TODO(deployments-v1): push filter state into the URL.+ })),+])diff --git a/products/deployments/frontend/generated/api.schemas.ts b/products/deployments/frontend/generated/api.schemas.tsnew file mode 100644index 000000000000..48351ccf75b3--- /dev/null+++ b/products/deployments/frontend/generated/api.schemas.ts@@ -0,0 +1,149 @@+/**+ * Auto-generated from the Django backend OpenAPI schema.+ * To modify these types, update the Django serializers or views, then run:+ * hogli build:openapi+ * Questions or issues? #team-devex on Slack+ *+ * PostHog API - generated+ * OpenAPI spec version: 1.0.0+ */+/**+ * * `queued` - Queued+ * `initializing` - Initializing+ * `building` - Building+ * `ready` - Ready+ * `error` - Error+ * `cancelled` - Cancelled+ */+export type DeploymentStatusEnumApi = (typeof DeploymentStatusEnumApi)[keyof typeof DeploymentStatusEnumApi]++export const DeploymentStatusEnumApi = {+ Queued: 'queued',+ Initializing: 'initializing',+ Building: 'building',+ Ready: 'ready',+ Error: 'error',+ Cancelled: 'cancelled',+} as const++/**+ * * `git` - Git+ * `redeploy` - Redeploy+ * `rollback` - Rollback+ * `seed` - Seed+ */+export type TriggerKindEnumApi = (typeof TriggerKindEnumApi)[keyof typeof TriggerKindEnumApi]++export const TriggerKindEnumApi = {+ Git: 'git',+ Redeploy: 'redeploy',+ Rollback: 'rollback',+ Seed: 'seed',+} as const++export interface DeploymentApi {+ /** Unique identifier for the deployment. */+ readonly id: string+ /** Current pipeline stage for the deployment. Valid values: queued, initializing, building, ready, error, cancelled.++ * `queued` - Queued+ * `initializing` - Initializing+ * `building` - Building+ * `ready` - Ready+ * `error` - Error+ * `cancelled` - Cancelled */+ status: DeploymentStatusEnumApi+ /**+ * Timestamp when the pipeline started building. Null while still queued.+ * @nullable+ */+ started_at?: string | null+ /**+ * Timestamp when the pipeline finished (regardless of outcome). Null while still running.+ * @nullable+ */+ finished_at?: string | null+ /** Timestamp when the deployment row was created. */+ readonly created_at: string+ /**+ * Git commit SHA the deployment was built from. Empty for non-git triggers.+ * @maxLength 64+ */+ commit_sha?: string+ /** Commit message associated with the commit SHA. */+ commit_message?: string+ /**+ * Display name of the commit author.+ * @maxLength 255+ */+ commit_author_name?: string+ /**+ * Email address of the commit author.+ * @maxLength 255+ */+ commit_author_email?: string+ /**+ * HTTPS URL of the source repository this deployment came from.+ * @maxLength 1024+ */+ repo_url?: string+ /**+ * Source branch the deployment was built from.+ * @maxLength 255+ */+ branch?: string+ /**+ * Public URL where the built site is served once the deployment is ready.+ * @maxLength 1024+ */+ deployment_url?: string+ /**+ * URL of a screenshot capture of the deployed site, used in the list view.+ * @maxLength 1024+ */+ preview_image_url?: string+ /**+ * The deployment this one was triggered from (e.g. for rollbacks/redeploys).+ * @nullable+ */+ readonly triggered_by_deployment: string | null+ /** What caused this deployment to start. One of: git, redeploy, rollback, seed.++ * `git` - Git+ * `redeploy` - Redeploy+ * `rollback` - Rollback+ * `seed` - Seed */+ trigger_kind: TriggerKindEnumApi+ /** Whether this deployment is the team's currently-serving production deployment. */+ readonly is_current: boolean+ /** Build duration in seconds (finished_at - started_at). 0 while still running. */+ readonly duration_seconds: number+}++export interface PaginatedDeploymentListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: DeploymentApi[]+}++/**+ * Response shape for the redeploy/rollback/refresh-preview stubs.+ */+export interface DeploymentActionResponseApi {+ /** Human-readable explanation of the stub response. */+ detail: string+}++export type DeploymentsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+}diff --git a/products/deployments/frontend/generated/api.ts b/products/deployments/frontend/generated/api.tsnew file mode 100644index 000000000000..0d7b69fe0ab5--- /dev/null+++ b/products/deployments/frontend/generated/api.ts@@ -0,0 +1,138 @@+import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'+/**+ * Auto-generated from the Django backend OpenAPI schema.+ * To modify these types, update the Django serializers or views, then run:+ * hogli build:openapi+ * Questions or issues? #team-devex on Slack+ *+ * PostHog API - generated+ * OpenAPI spec version: 1.0.0+ */+import type { DeploymentApi, DeploymentsListParams, PaginatedDeploymentListApi } from './api.schemas'++export const getDeploymentsListUrl = (projectId: string, params?: DeploymentsListParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : value.toString())+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/deployments/?${stringifiedParams}`+ : `/api/projects/${projectId}/deployments/`+}++/**+ * Read-only viewset for the Deployments product.++`list` and `retrieve` are wired against the model queryset. The+`@action` stubs (`redeploy`, `rollback`, `refresh_preview`) intentionally+return 501 — they exist so OpenAPI / MCP can discover the surface area+while behavior lands in follow-up commits.+ */+export const deploymentsList = async (+ projectId: string,+ params?: DeploymentsListParams,+ options?: RequestInit+): Promise<PaginatedDeploymentListApi> => {+ return apiMutator<PaginatedDeploymentListApi>(getDeploymentsListUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}++export const getDeploymentsRetrieveUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/deployments/${id}/`+}++/**+ * Read-only viewset for the Deployments product.++`list` and `retrieve` are wired against the model queryset. The+`@action` stubs (`redeploy`, `rollback`, `refresh_preview`) intentionally+return 501 — they exist so OpenAPI / MCP can discover the surface area+while behavior lands in follow-up commits.+ */+export const deploymentsRetrieve = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<DeploymentApi> => {+ return apiMutator<DeploymentApi>(getDeploymentsRetrieveUrl(projectId, id), {+ ...options,+ method: 'GET',+ })+}++export const getDeploymentsRedeployCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/deployments/${id}/redeploy/`+}++/**+ * Read-only viewset for the Deployments product.++`list` and `retrieve` are wired against the model queryset. The+`@action` stubs (`redeploy`, `rollback`, `refresh_preview`) intentionally+return 501 — they exist so OpenAPI / MCP can discover the surface area+while behavior lands in follow-up commits.+ */+export const deploymentsRedeployCreate = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<unknown> => {+ return apiMutator<unknown>(getDeploymentsRedeployCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ })+}++export const getDeploymentsRefreshPreviewCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/deployments/${id}/refresh-preview/`+}++/**+ * Read-only viewset for the Deployments product.++`list` and `retrieve` are wired against the model queryset. The+`@action` stubs (`redeploy`, `rollback`, `refresh_preview`) intentionally+return 501 — they exist so OpenAPI / MCP can discover the surface area+while behavior lands in follow-up commits.+ */+export const deploymentsRefreshPreviewCreate = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<unknown> => {+ return apiMutator<unknown>(getDeploymentsRefreshPreviewCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ })+}++export const getDeploymentsRollbackCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/deployments/${id}/rollback/`+}++/**+ * Read-only viewset for the Deployments product.++`list` and `retrieve` are wired against the model queryset. The+`@action` stubs (`redeploy`, `rollback`, `refresh_preview`) intentionally+return 501 — they exist so OpenAPI / MCP can discover the surface area+while behavior lands in follow-up commits.+ */+export const deploymentsRollbackCreate = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<unknown> => {+ return apiMutator<unknown>(getDeploymentsRollbackCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ })+}diff --git a/products/deployments/frontend/generated/api.zod.schemas.ts b/products/deployments/frontend/generated/api.zod.schemas.tsnew file mode 100644index 000000000000..15514d6bd13f--- /dev/null+++ b/products/deployments/frontend/generated/api.zod.schemas.ts@@ -0,0 +1,222 @@+/**+ * Auto-generated Zod validation schemas from the Django backend OpenAPI schema.+ * To modify these schemas, update the Django serializers or views, then run:+ * hogli build:openapi+ * Questions or issues? #team-devex on Slack+ *+ * PostHog API - generated+ * OpenAPI spec version: 1.0.0+ */+import { z as zod } from 'zod'++export const DeploymentStatusEnumApi = zod+ .enum(['queued', 'initializing', 'building', 'ready', 'error', 'cancelled'])+ .describe(+ '\* `queued` - Queued\n\* `initializing` - Initializing\n\* `building` - Building\n\* `ready` - Ready\n\* `error` - Error\n\* `cancelled` - Cancelled'+ )++export type DeploymentStatusEnumApi = zod.input<typeof DeploymentStatusEnumApi>+export type DeploymentStatusEnumApiOutput = zod.output<typeof DeploymentStatusEnumApi>++export const TriggerKindEnumApi = zod+ .enum(['git', 'redeploy', 'rollback', 'seed'])+ .describe('\* `git` - Git\n\* `redeploy` - Redeploy\n\* `rollback` - Rollback\n\* `seed` - Seed')++export type TriggerKindEnumApi = zod.input<typeof TriggerKindEnumApi>+export type TriggerKindEnumApiOutput = zod.output<typeof TriggerKindEnumApi>++export const deploymentApiCommitShaMax = 64++export const deploymentApiCommitAuthorNameMax = 255++export const deploymentApiCommitAuthorEmailMax = 255++export const deploymentApiRepoUrlMax = 1024++export const deploymentApiBranchMax = 255++export const deploymentApiDeploymentUrlMax = 1024++export const deploymentApiPreviewImageUrlMax = 1024++export const DeploymentApi = zod.object({+ id: zod.uuid().describe('Unique identifier for the deployment.'),+ status: zod+ .enum(['queued', 'initializing', 'building', 'ready', 'error', 'cancelled'])+ .describe(+ '\* `queued` - Queued\n\* `initializing` - Initializing\n\* `building` - Building\n\* `ready` - Ready\n\* `error` - Error\n\* `cancelled` - Cancelled'+ )+ .describe(+ 'Current pipeline stage for the deployment. Valid values: queued, initializing, building, ready, error, cancelled.\n\n\* `queued` - Queued\n\* `initializing` - Initializing\n\* `building` - Building\n\* `ready` - Ready\n\* `error` - Error\n\* `cancelled` - Cancelled'+ ),+ started_at: zod.iso+ .datetime({ offset: true })+ .nullish()+ .describe('Timestamp when the pipeline started building. Null while still queued.'),+ finished_at: zod.iso+ .datetime({ offset: true })+ .nullish()+ .describe('Timestamp when the pipeline finished (regardless of outcome). Null while still running.'),+ created_at: zod.iso.datetime({ offset: true }).describe('Timestamp when the deployment row was created.'),+ commit_sha: zod+ .string()+ .max(deploymentApiCommitShaMax)+ .optional()+ .describe('Git commit SHA the deployment was built from. Empty for non-git triggers.'),+ commit_message: zod.string().optional().describe('Commit message associated with the commit SHA.'),+ commit_author_name: zod+ .string()+ .max(deploymentApiCommitAuthorNameMax)+ .optional()+ .describe('Display name of the commit author.'),+ commit_author_email: zod+ .string()+ .max(deploymentApiCommitAuthorEmailMax)+ .optional()+ .describe('Email address of the commit author.'),+ repo_url: zod+ .url()+ .max(deploymentApiRepoUrlMax)+ .optional()+ .describe('HTTPS URL of the source repository this deployment came from.'),+ branch: zod+ .string()+ .max(deploymentApiBranchMax)+ .optional()+ .describe('Source branch the deployment was built from.'),+ deployment_url: zod+ .url()+ .max(deploymentApiDeploymentUrlMax)+ .optional()+ .describe('Public URL where the built site is served once the deployment is ready.'),+ preview_image_url: zod+ .url()+ .max(deploymentApiPreviewImageUrlMax)+ .optional()+ .describe('URL of a screenshot capture of the deployed site, used in the list view.'),+ triggered_by_deployment: zod+ .uuid()+ .nullable()+ .describe('The deployment this one was triggered from (e.g. for rollbacks\/redeploys).'),+ trigger_kind: zod+ .enum(['git', 'redeploy', 'rollback', 'seed'])+ .describe('\* `git` - Git\n\* `redeploy` - Redeploy\n\* `rollback` - Rollback\n\* `seed` - Seed')+ .describe(+ 'What caused this deployment to start. One of: git, redeploy, rollback, seed.\n\n\* `git` - Git\n\* `redeploy` - Redeploy\n\* `rollback` - Rollback\n\* `seed` - Seed'+ ),+ is_current: zod+ .boolean()+ .describe("Whether this deployment is the team's currently-serving production deployment."),+ duration_seconds: zod+ .number()+ .describe('Build duration in seconds (finished_at - started_at). 0 while still running.'),+})++export type DeploymentApi = zod.input<typeof DeploymentApi>+export type DeploymentApiOutput = zod.output<typeof DeploymentApi>++export const paginatedDeploymentListApiResultsItemCommitShaMax = 64++export const paginatedDeploymentListApiResultsItemCommitAuthorNameMax = 255++export const paginatedDeploymentListApiResultsItemCommitAuthorEmailMax = 255++export const paginatedDeploymentListApiResultsItemRepoUrlMax = 1024++export const paginatedDeploymentListApiResultsItemBranchMax = 255++export const paginatedDeploymentListApiResultsItemDeploymentUrlMax = 1024++export const paginatedDeploymentListApiResultsItemPreviewImageUrlMax = 1024++export const PaginatedDeploymentListApi = zod.object({+ count: zod.number(),+ next: zod.url().nullish(),+ previous: zod.url().nullish(),+ results: zod.array(+ zod.object({+ id: zod.uuid().describe('Unique identifier for the deployment.'),+ status: zod+ .enum(['queued', 'initializing', 'building', 'ready', 'error', 'cancelled'])+ .describe(+ '\* `queued` - Queued\n\* `initializing` - Initializing\n\* `building` - Building\n\* `ready` - Ready\n\* `error` - Error\n\* `cancelled` - Cancelled'+ )+ .describe(+ 'Current pipeline stage for the deployment. Valid values: queued, initializing, building, ready, error, cancelled.\n\n\* `queued` - Queued\n\* `initializing` - Initializing\n\* `building` - Building\n\* `ready` - Ready\n\* `error` - Error\n\* `cancelled` - Cancelled'+ ),+ started_at: zod.iso+ .datetime({ offset: true })+ .nullish()+ .describe('Timestamp when the pipeline started building. Null while still queued.'),+ finished_at: zod.iso+ .datetime({ offset: true })+ .nullish()+ .describe('Timestamp when the pipeline finished (regardless of outcome). Null while still running.'),+ created_at: zod.iso.datetime({ offset: true }).describe('Timestamp when the deployment row was created.'),+ commit_sha: zod+ .string()+ .max(paginatedDeploymentListApiResultsItemCommitShaMax)+ .optional()+ .describe('Git commit SHA the deployment was built from. Empty for non-git triggers.'),+ commit_message: zod.string().optional().describe('Commit message associated with the commit SHA.'),+ commit_author_name: zod+ .string()+ .max(paginatedDeploymentListApiResultsItemCommitAuthorNameMax)+ .optional()+ .describe('Display name of the commit author.'),+ commit_author_email: zod+ .string()+ .max(paginatedDeploymentListApiResultsItemCommitAuthorEmailMax)+ .optional()+ .describe('Email address of the commit author.'),+ repo_url: zod+ .url()+ .max(paginatedDeploymentListApiResultsItemRepoUrlMax)+ .optional()+ .describe('HTTPS URL of the source repository this deployment came from.'),+ branch: zod+ .string()+ .max(paginatedDeploymentListApiResultsItemBranchMax)+ .optional()+ .describe('Source branch the deployment was built from.'),+ deployment_url: zod+ .url()+ .max(paginatedDeploymentListApiResultsItemDeploymentUrlMax)+ .optional()+ .describe('Public URL where the built site is served once the deployment is ready.'),+ preview_image_url: zod+ .url()+ .max(paginatedDeploymentListApiResultsItemPreviewImageUrlMax)+ .optional()+ .describe('URL of a screenshot capture of the deployed site, used in the list view.'),+ triggered_by_deployment: zod+ .uuid()+ .nullable()+ .describe('The deployment this one was triggered from (e.g. for rollbacks\/redeploys).'),+ trigger_kind: zod+ .enum(['git', 'redeploy', 'rollback', 'seed'])+ .describe('\* `git` - Git\n\* `redeploy` - Redeploy\n\* `rollback` - Rollback\n\* `seed` - Seed')+ .describe(+ 'What caused this deployment to start. One of: git, redeploy, rollback, seed.\n\n\* `git` - Git\n\* `redeploy` - Redeploy\n\* `rollback` - Rollback\n\* `seed` - Seed'+ ),+ is_current: zod+ .boolean()+ .describe("Whether this deployment is the team's currently-serving production deployment."),+ duration_seconds: zod+ .number()+ .describe('Build duration in seconds (finished_at - started_at). 0 while still running.'),+ })+ ),+})++export type PaginatedDeploymentListApi = zod.input<typeof PaginatedDeploymentListApi>+export type PaginatedDeploymentListApiOutput = zod.output<typeof PaginatedDeploymentListApi>++export const DeploymentActionResponseApi = zod+ .object({+ detail: zod.string().describe('Human-readable explanation of the stub response.'),+ })+ .describe('Response shape for the redeploy\/rollback\/refresh-preview stubs.')++export type DeploymentActionResponseApi = zod.input<typeof DeploymentActionResponseApi>+export type DeploymentActionResponseApiOutput = zod.output<typeof DeploymentActionResponseApi>diff --git a/products/deployments/frontend/generated/api.zod.ts b/products/deployments/frontend/generated/api.zod.tsnew file mode 100644index 000000000000..e8a15d4e1b52--- /dev/null+++ b/products/deployments/frontend/generated/api.zod.ts@@ -0,0 +1,9 @@+/**+ * Auto-generated Zod validation schemas from the Django backend OpenAPI schema.+ * To modify these schemas, update the Django serializers or views, then run:+ * hogli build:openapi+ * Questions or issues? #team-devex on Slack+ *+ * PostHog API - generated+ * OpenAPI spec version: 1.0.0+ */diff --git a/products/deployments/manifest.tsx b/products/deployments/manifest.tsxnew file mode 100644index 000000000000..2c0a51710afc--- /dev/null+++ b/products/deployments/manifest.tsx@@ -0,0 +1,49 @@+import { FEATURE_FLAGS } from 'lib/constants'+import { urls } from 'scenes/urls'++import { FileSystemIconType, ProductItemCategory, ProductKey } from '~/queries/schema/schema-general'++import { FileSystemIconColor, ProductManifest } from '../../frontend/src/types'++export const manifest: ProductManifest = {+ name: 'Deployments',+ scenes: {+ Deployments: {+ import: () => import('./frontend/Deployments'),+ projectBased: true,+ name: 'Deployments',+ iconType: 'live',+ description: 'Build and ship your project site straight from PostHog.',+ },+ Deployment: {+ import: () => import('./frontend/Deployment'),+ projectBased: true,+ name: 'Deployment',+ },+ },+ routes: {+ '/deployments': ['Deployments', 'deployments'],+ '/deployments/:id': ['Deployment', 'deployment'],+ },+ urls: {+ deployments: (): string => '/deployments',+ deployment: (id: string): string => `/deployments/${id}`,+ },+ fileSystemTypes: {},+ treeItemsNew: [],+ treeItemsProducts: [+ {+ path: 'Deployments',+ intents: [ProductKey.DEPLOYMENTS],+ category: ProductItemCategory.TOOLS,+ href: urls.deployments(),+ type: 'live',+ iconType: 'live' as FileSystemIconType,+ iconColor: ['var(--color-text-3000)'] as FileSystemIconColor,+ sceneKey: 'Deployments',+ sceneKeys: ['Deployments', 'Deployment'],+ flag: FEATURE_FLAGS.DEPLOYMENTS,+ tags: ['alpha'],+ },+ ],+}diff --git a/products/deployments/package.json b/products/deployments/package.jsonnew file mode 100644index 000000000000..07acb64e4684--- /dev/null+++ b/products/deployments/package.json@@ -0,0 +1,20 @@+{+ "name": "@posthog/products-deployments",+ "scripts": {+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/test -v --tb=short"+ },+ "dependencies": {+ "kea": "catalog:",+ "kea-loaders": "catalog:",+ "kea-router": "catalog:",+ "posthog-js": "catalog:"+ },+ "devDependencies": {+ "kea-test-utils": "catalog:"+ },+ "peerDependencies": {+ "@posthog/icons": "*",+ "@types/react": "*",+ "react": "*"+ }+}diff --git a/products/deployments/product.yaml b/products/deployments/product.yamlnew file mode 100644index 000000000000..1870b57f5137--- /dev/null+++ b/products/deployments/product.yaml@@ -0,0 +1,3 @@+name: Deployments+owners:+ - '@richardsolomou'diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 403d24e5d9f4..e364def02b85 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -11845,6 +11845,129 @@ export namespace Schemas {name: string;}+ /**+ * * `queued` - Queued+ * `initializing` - Initializing+ * `building` - Building+ * `ready` - Ready+ * `error` - Error+ * `cancelled` - Cancelled+ */+ export type DeploymentStatusEnum = typeof DeploymentStatusEnum[keyof typeof DeploymentStatusEnum];+++ export const DeploymentStatusEnum = {+ Queued: 'queued',+ Initializing: 'initializing',+ Building: 'building',+ Ready: 'ready',+ Error: 'error',+ Cancelled: 'cancelled',+ } as const;++ /**+ * * `git` - Git+ * `redeploy` - Redeploy+ * `rollback` - Rollback+ * `seed` - Seed+ */+ export type TriggerKindEnum = typeof TriggerKindEnum[keyof typeof TriggerKindEnum];+++ export const TriggerKindEnum = {+ Git: 'git',+ Redeploy: 'redeploy',+ Rollback: 'rollback',+ Seed: 'seed',+ } as const;++ export interface Deployment {+ /** Unique identifier for the deployment. */+ readonly id: string;+ /** Current pipeline stage for the deployment. Valid values: queued, initializing, building, ready, error, cancelled.++ * `queued` - Queued+ * `initializing` - Initializing+ * `building` - Building+ * `ready` - Ready+ * `error` - Error+ * `cancelled` - Cancelled */+ status: DeploymentStatusEnum;+ /**+ * Timestamp when the pipeline started building. Null while still queued.+ * @nullable+ */+ started_at?: string | null;+ /**+ * Timestamp when the pipeline finished (regardless of outcome). Null while still running.+ * @nullable+ */+ finished_at?: string | null;+ /** Timestamp when the deployment row was created. */+ readonly created_at: string;+ /**+ * Git commit SHA the deployment was built from. Empty for non-git triggers.+ * @maxLength 64+ */+ commit_sha?: string;+ /** Commit message associated with the commit SHA. */+ commit_message?: string;+ /**+ * Display name of the commit author.+ * @maxLength 255+ */+ commit_author_name?: string;+ /**+ * Email address of the commit author.+ * @maxLength 255+ */+ commit_author_email?: string;+ /**+ * HTTPS URL of the source repository this deployment came from.+ * @maxLength 1024+ */+ repo_url?: string;+ /**+ * Source branch the deployment was built from.+ * @maxLength 255+ */+ branch?: string;+ /**+ * Public URL where the built site is served once the deployment is ready.+ * @maxLength 1024+ */+ deployment_url?: string;+ /**+ * URL of a screenshot capture of the deployed site, used in the list view.+ * @maxLength 1024+ */+ preview_image_url?: string;+ /**+ * The deployment this one was triggered from (e.g. for rollbacks/redeploys).+ * @nullable+ */+ readonly triggered_by_deployment: string | null;+ /** What caused this deployment to start. One of: git, redeploy, rollback, seed.++ * `git` - Git+ * `redeploy` - Redeploy+ * `rollback` - Rollback+ * `seed` - Seed */+ trigger_kind: TriggerKindEnum;+ /** Whether this deployment is the team's currently-serving production deployment. */+ readonly is_current: boolean;+ /** Build duration in seconds (finished_at - started_at). 0 while still running. */+ readonly duration_seconds: number;+ }++ /**+ * Response shape for the redeploy/rollback/refresh-preview stubs.+ */+ export interface DeploymentActionResponse {+ /** Human-readable explanation of the stub response. */+ detail: string;+ }+export interface DeprovisionWarehouseResponse {status: string;team: string;@@ -21025,6 +21148,15 @@ export namespace Schemas {results: Dataset[];}+ export interface PaginatedDeploymentList {+ count: number;+ /** @nullable */+ next?: string | null;+ /** @nullable */+ previous?: string | null;+ results: Deployment[];+ }+export interface PaginatedDesktopRecordingList {count: number;/** @nullable */@@ -40673,6 +40805,17 @@ export namespace Schemas {search?: string;};+ export type DeploymentsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number;+ /**+ * The initial index from which to return the results.+ */+ offset?: number;+ };+export type EarlyAccessFeatureListParams = {/*** Number of results to return per page.diff --git a/tach.toml b/tach.tomlindex 6c1a9c52ac91..f22fc10521de 100644--- a/tach.toml+++ b/tach.toml@@ -66,6 +66,7 @@ depends_on = ["products.dashboards","products.data_modeling","products.data_warehouse",+ "products.deployments","products.desktop_recordings","products.early_access_features","products.endpoints",@@ -177,6 +178,13 @@ depends_on = []layer = "modules"+[[modules]]+path = "products.deployments"+depends_on = [+ "posthog",+]+layer = "modules"+[[modules]]path = "products.desktop_recordings"depends_on = [