: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(tasks): add agent infrastructure release admin (#109246)
Alessandro Pogliaghi7f5d06950785
diff --git a/.oxlintrc.json b/.oxlintrc.jsonindex 5c68a3045c61..1fe96b0cb0c9 100644--- a/.oxlintrc.json+++ b/.oxlintrc.json@@ -238,7 +238,11 @@}},{- "files": ["services/mcp/src/ui-apps/**/*.{ts,tsx}", "products/**/mcp/apps/**/*.{ts,tsx}"],+ "files": [+ "services/mcp/src/ui-apps/**/*.{ts,tsx}",+ "products/**/mcp/apps/**/*.{ts,tsx}",+ "products/tasks/frontend/infrastructure/**/*.{ts,tsx}"+ ],"rules": {"react/forbid-elements": "off"}diff --git a/docs/internal/sandboxes-setup-guide.md b/docs/internal/sandboxes-setup-guide.mdindex f8d052dae6e7..e518133c1749 100644--- a/docs/internal/sandboxes-setup-guide.md+++ b/docs/internal/sandboxes-setup-guide.md@@ -379,6 +379,12 @@ in a production app. A new app name has to be a class attribute for that to keep### Sandbox templates+Staff can inspect the agent release pipeline at `/admin/tasks/task/infrastructure/` in each region.+The read-only page compares the published package, master version pin, registry platforms, custom-image bases, and the last recorded dev-stack bake.+Release evidence separates workflow status from image build and base promotion results, including skipped builds.+Select a custom image to inspect its latest Temporal execution. A failed refresh can leave a ready image on an older base.+Missing or stale sources remain unverified. This view does not measure versions inside running sandboxes or reconstruct historical rollout completion.+Each sandbox is created from a template that determines its base image and capabilities.| Template | Image | Description |diff --git a/frontend/build.mjs b/frontend/build.mjsindex e2d4a56d51fc..ed4745846162 100755--- a/frontend/build.mjs+++ b/frontend/build.mjs@@ -42,6 +42,7 @@ copyRRWebWorkerFiles(__dirname)writeIndexHtml()writeExporterHtml()writeRenderQueryHtml()+writeInfrastructureAdminHtml()await import('./build-products.mjs')const common = {@@ -90,6 +91,13 @@ await buildInParallel(outfile: path.resolve(__dirname, 'dist', 'render-query.js'),...common,},+ {+ name: 'Infrastructure Admin',+ entryPoints: ['../products/tasks/frontend/infrastructure/mountInfrastructureAdmin.tsx'],+ format: 'iife',+ outfile: path.resolve(__dirname, 'dist', 'infrastructure-admin.js'),+ ...common,+ },{...getToolbarAppBuildConfig(__dirname),...common,@@ -155,6 +163,10 @@ await buildInParallel(writeRenderQueryHtml(chunks, entrypoints)}+ if (config.name === 'Infrastructure Admin') {+ writeInfrastructureAdminHtml(chunks, entrypoints)+ }+if (config.name === 'Toolbar') {await finalizeToolbarBuild(__dirname, buildResponse)}@@ -241,6 +253,17 @@ export function writeExporterHtml(chunks = {}, entrypoints = []) {copyIndexHtml(__dirname, 'src/exporter/index.html', 'dist/exporter.html', 'exporter', chunks, entrypoints)}+export function writeInfrastructureAdminHtml(chunks = {}, entrypoints = []) {+ copyIndexHtml(+ __dirname,+ '../products/tasks/frontend/infrastructure/infrastructureAdmin.html',+ 'dist/infrastructure_admin.html',+ 'infrastructure-admin',+ chunks,+ entrypoints+ )+}+export function writeRenderQueryHtml(chunks = {}, entrypoints = []) {copyIndexHtml(__dirname,diff --git a/frontend/plugins/vite-html-plugin.ts b/frontend/plugins/vite-html-plugin.tsindex 172798039cd4..253ba33a770a 100644--- a/frontend/plugins/vite-html-plugin.ts+++ b/frontend/plugins/vite-html-plugin.ts@@ -2,8 +2,20 @@ import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'import { dirname, resolve } from 'path'import type { Plugin } from 'vite'-const srcHtmlFiles = ['src/index.html', 'src/layout.html', 'src/exporter/index.html', 'src/render-query/index.html']-const distHtmlFiles = ['dist/index.html', 'dist/layout.html', 'dist/exporter.html', 'dist/render_query.html']+const srcHtmlFiles = [+ 'src/index.html',+ 'src/layout.html',+ 'src/exporter/index.html',+ 'src/render-query/index.html',+ '../products/tasks/frontend/infrastructure/infrastructureAdmin.html',+]+const distHtmlFiles = [+ 'dist/index.html',+ 'dist/layout.html',+ 'dist/exporter.html',+ 'dist/render_query.html',+ 'dist/infrastructure_admin.html',+]function deleteHtmlFiles(): void {distHtmlFiles.forEach((file) => {@@ -32,9 +44,21 @@ function copyHtmlFile(from: string, to: string): void {mkdirSync(toDir, { recursive: true })}- // Copy the HTML file without modification (preserve Django template syntax)const htmlContent = readFileSync(fromPath, 'utf-8')- writeFileSync(toPath, htmlContent)+ const content =+ to === 'dist/infrastructure_admin.html'+ ? htmlContent.replace(+ '</head>',+ `<script type="module" nonce="{{ request.csp_nonce }}">+ import RefreshRuntime from '{{ js_url|escapejs }}/@react-refresh'+ RefreshRuntime.injectIntoGlobalHook(window)+ window.$RefreshReg$ = () => {}+ window.$RefreshSig$ = () => (type) => type+ window.__vite_plugin_react_preamble_installed__ = true+ </script><script type="module" src="{{ js_url }}/@vite/client"></script><script type="module" src="{{ js_url }}/@fs${resolve('../products/tasks/frontend/infrastructure/mountInfrastructureAdmin.tsx')}"></script></head>`+ )+ : htmlContent+ writeFileSync(toPath, content)console.info(`✨ Copied ${from} to ${to}`)} catch (error) {console.warn(`❌ Could not copy ${from} to ${to}:`, error)diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 37d2b6b72c19..b12c78555e44 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -7130,6 +7130,22 @@ snapshots:hash: v1.k794b7964.79b55888f68b8fdecde60eb59f9941838eed95754b51bd361ab65be360277270.lJwqiaG6UTf6bczX7v1jw_bImsnq7LK-tuxsBFZt2F4products-subscriptions-subscriptions-table--with-pagination--light:hash: v1.k794b7964.c54c1003b71f29a08808fa1e4e7413ee7c61f514eb1198c924d936cc95c834e5.1PL1n6t2LsJ6X33Z6txXpmifcmqNP6HrVtrLhnMrWMA+ products-tasks-infrastructure-admin--awaiting-pin--dark:+ hash: v1.k794b7964.b331773e650f3814efa771ab8b32c8e66c563b1b0360cde5121a181fc5462717.UYUmVzEWVr8qigZH8qRiXa1_7PGDoEEv9xy1yuFSLJk+ products-tasks-infrastructure-admin--awaiting-pin--light:+ hash: v1.k794b7964.405694015db96ed95c1f66ed618843bfe79f69ca60579b535e80a8ab4d90ff8f.DJOz93cqatah7EDNwPXP8bL1GXe2fALdFI-2hdSajKA+ products-tasks-infrastructure-admin--narrow--dark:+ hash: v1.k794b7964.19e2b4eedfa858e97b329167a99067c237a31913024c6f5f304cea5f4b8d07da.tpH_j31SSyiHMGSWG0CRKRKeQ4LrFp_y3ryjNabxiTo+ products-tasks-infrastructure-admin--narrow--light:+ hash: v1.k794b7964.64de379b2dd92d1becc68ac09c5ae5a29da3f40c69bfce31baa78467c9495025.2FkqZYE31H1NuTuV-G9dU-f_3kVrHvno4kM7EhaB_II+ products-tasks-infrastructure-admin--rolling-out--dark:+ hash: v1.k794b7964.c8d441069bb006547cbbb32db84233d4b205116effbef92c1f41f3709cd75f77.bH9rqew-wPGXn8ZevKbA_puMvskQO7C0ezUXyWCgqlg+ products-tasks-infrastructure-admin--rolling-out--light:+ hash: v1.k794b7964.020c96bacfd2998c676a9be37c03487621a5e0c259aeabb5760d3bca3b5de46a.EBdT6IBK0hAm0OpjQlUEnrApTl03IQ7Ylczgy1fUYy0+ products-tasks-infrastructure-admin--unavailable--dark:+ hash: v1.k794b7964.8392888d1451f2e1acffebc341b8b03bbdbea75fdd0247c3d13dc9d863d4f797.eJXrTs0V9AyaT_dG1xQD40Pjx4G7_qCwxX1sQGr7UNs+ products-tasks-infrastructure-admin--unavailable--light:+ hash: v1.k794b7964.a5e5d20f5b00a5dc8fb93a713ded98c230517d1910604f8b380992720d9f82b4.55AgBX1suG_-a-UMTZvfgMD4UTbiv9My5Wg7R2ZeY9Aproducts-tracing-operationstable--default--dark:hash: v1.k794b7964.58421fb9485687230fc55051bb13eeefff6fec4dbc8cc0eeb9a9a9f3f39a30cd.QacFiUZLBgSAOZZnr3OoUeIP2e-0gBXYobLZf-MTcMMproducts-tracing-operationstable--default--light:diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 31d51a731968..51536dc4172f 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -4997,6 +4997,9 @@ importers:kea:specifier: 'catalog:'version: 4.0.0-pre.6(patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected])+ kea-disposables:+ specifier: 'catalog:'+ version: 1.0.0([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))kea-loaders:specifier: 'catalog:'version: 3.1.1([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))@@ -5016,6 +5019,9 @@ importers:kea-test-utils:specifier: 'catalog:'version: 0.2.4([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))+ tailwindcss:+ specifier: 4.3.0+ version: 4.3.0products/today: {}diff --git a/posthog/csp_middleware.py b/posthog/csp_middleware.pyindex ee9ff11552a3..85fb259dc699 100644--- a/posthog/csp_middleware.py+++ b/posthog/csp_middleware.py@@ -238,10 +238,15 @@ class CSPMiddleware:is_admin_view = getattr(settings, "ADMIN_PORTAL_ENABLED", False) and request.path.startswith("/admin/")if is_admin_view:django_loginas_inline_script_hash = "sha256-2bSkJXtgXFhxZUhgXzWsEsKImxJEQsqjns0vi3KiSrI="+ admin_bundle_origin = ""+ if request.path == "/admin/tasks/task/infrastructure/":+ bundle_url = urlsplit(settings.JS_URL)+ if bundle_url.scheme in ("http", "https") and bundle_url.netloc:+ admin_bundle_origin = f"{bundle_url.scheme}://{bundle_url.netloc}"csp_parts = ["default-src 'self'",- "style-src 'self' 'unsafe-inline'",- f"script-src 'self' 'nonce-{nonce}' '{django_loginas_inline_script_hash}'",+ f"style-src 'self' 'unsafe-inline' {admin_bundle_origin}".rstrip(),+ f"script-src 'self' 'nonce-{nonce}' '{django_loginas_inline_script_hash}' {admin_bundle_origin}".rstrip(),"font-src data: https://fonts.gstatic.com",# Without this the directive falls back to `default-src 'self'`, which drops the# `data:` icons Django admin and our own admin pages render, and the `blob:` images@@ -258,6 +263,9 @@ class CSPMiddleware:"frame-src https://posthog.com","base-uri 'self'",]+ if admin_bundle_origin and settings.DEBUG:+ websocket_origin = admin_bundle_origin.replace("https://", "wss://").replace("http://", "ws://")+ csp_parts.append(f"connect-src 'self' {admin_bundle_origin} {websocket_origin}")admin_report_endpoint = csp_report_endpoint()if admin_report_endpoint:diff --git a/posthog/egress/github/README.md b/posthog/egress/github/README.mdindex 90762d01aa8f..09d6a0dfef0d 100644--- a/posthog/egress/github/README.md+++ b/posthog/egress/github/README.md@@ -30,6 +30,7 @@ The warehouse source's page fetches run on `BATCH`, while its repository validatThe ownership file reader (`posthog/ownership/`, source `ownership_github_api`) runs on `NORMAL` where a person waits for a board or a snapshot list, and on `BATCH` for the scheduled digests and report generation. Its GraphQL reads charge `core`, as every GraphQL call does, and so does the one compare call per new head commit that lets it reuse cached files.Stamphog reads the author-familiarity blame and history (GraphQL) and the pull request's commit messages on `BATCH`, because both signals are advisory: a shed call leaves them out of that review.Its merge base read (compare) stays on the default lane, because the review checkout needs it.+The Tasks infrastructure admin reads the sandbox version pin and recent image build runs on `NORMAL`, using the shared token and a regional cache.The `BATCH` floor on the `core` resource is **demand-responsive**, because a reserve is only worth holding against traffic that exists.An installation whose only consumer is a bulk one (a warehouse backfill of a repository nothing else touches) would otherwise forfeit 30% of its hourly budget to contention that never arrives, and the hourly budget is what decides whether a large backfill finishes in one run.diff --git a/products/tasks/backend/admin.py b/products/tasks/backend/admin.pyindex 71b3bc9411eb..cfe5bffbdf84 100644--- a/products/tasks/backend/admin.py+++ b/products/tasks/backend/admin.py@@ -18,6 +18,7 @@ from . import loop_servicefrom .logic.services.ai_run_defaults import validate_ai_run_preferences_payloadfrom .loop_lifecycle import DISABLED_REASON_ADMIN_PAUSED, pause_loopfrom .models import Loop, LoopTrigger, SandboxSnapshot, Task, TaskRun, TeamTasksConfig, UserTasksConfig+from .presentation.views.infrastructure_admin import infrastructure_adminfrom .visibility import task_run_visibility_q, task_visibility_qlogger = logging.getLogger(__name__)@@ -25,6 +26,14 @@ logger = logging.getLogger(__name__)@admin.register(Task)class TaskAdmin(admin.ModelAdmin):+ change_list_template = "admin/tasks/task/change_list.html"++ def get_urls(self) -> list:+ return [+ path("infrastructure/", self.admin_site.admin_view(infrastructure_admin), name="tasks_infrastructure"),+ *super().get_urls(),+ ]+list_display = ("slug", "title", "origin_product", "internal", "team", "created_by", "created_at", "deleted")list_filter = ("origin_product", "internal", "deleted", "created_at")search_fields = ("title", "description", "repository")diff --git a/products/tasks/backend/facade/infrastructure.py b/products/tasks/backend/facade/infrastructure.pynew file mode 100644index 000000000000..737b9f82a490--- /dev/null+++ b/products/tasks/backend/facade/infrastructure.py@@ -0,0 +1,4 @@+from products.tasks.backend.constants import DEV_STACK_IMAGE_NAME+from products.tasks.backend.logic.services.infrastructure_status import IMAGE_NAMES, InfrastructureStatus++__all__ = ["DEV_STACK_IMAGE_NAME", "IMAGE_NAMES", "InfrastructureStatus"]diff --git a/products/tasks/backend/logic/services/infrastructure_status.py b/products/tasks/backend/logic/services/infrastructure_status.pynew file mode 100644index 000000000000..f6127ac5cbcc--- /dev/null+++ b/products/tasks/backend/logic/services/infrastructure_status.py@@ -0,0 +1,267 @@+import re+import base64+import asyncio+import logging+from collections.abc import Callable+from contextlib import suppress+from datetime import datetime, timedelta+from typing import Literal, cast+from urllib.parse import quote++from django.conf import settings+from django.db.models import BooleanField, Case, Value, When+from django.utils import timezone++import requests+from asgiref.sync import async_to_sync+from pydantic import BaseModel, JsonValue+from redis.exceptions import LockNotOwnedError+from temporalio.api.enums.v1 import PendingActivityState+from temporalio.service import RPCError, RPCStatusCode++from posthog.egress.github.transport import github_request+from posthog.egress.limiter.policies import Priority+from posthog.temporal.common.client import async_connect++from products.tasks.backend.constants import DEV_STACK_IMAGE_NAME+from products.tasks.backend.models import SandboxCustomImage+from products.tasks.backend.redis import get_tasks_cache, get_tasks_stream_redis_sync++logger = logging.getLogger(__name__)++IMAGE_NAMES = ("base", "notebook", "streamlit", "pi", "autoresearch", "vm")+MAX_IMAGES = 1000+CACHE_SECONDS = 60+++class SourceSnapshot(BaseModel):+ status: Literal["ok", "error", "refreshing"]+ observed_at: datetime | None = None+ data: JsonValue = None+++class CustomImageStatus(BaseModel):+ id: str+ team_id: int+ status: str+ version: int+ base_image_reference: str | None+ base_image_refresh_reference: str | None+ has_published_image: bool+ has_error: bool+ has_spec: bool+ updated_at: datetime+ workflow_url: str+++def workflow_url(workflow_id: str) -> str:+ return (+ f"{settings.TEMPORAL_UI_HOST.rstrip('/')}/namespaces/{quote(settings.TEMPORAL_NAMESPACE, safe='')}"+ f"/workflows/{quote(workflow_id, safe='')}"+ )+++class InfrastructureStatus:+ def _json(self, url: str, *, headers: dict[str, str] | None = None) -> requests.Response:+ response = requests.get(url, headers=headers, timeout=5)+ response.raise_for_status()+ return response++ def _github(self, path: str) -> dict[str, JsonValue]:+ headers = {"Authorization": f"Bearer {settings.GITHUB_TOKEN}"} if settings.GITHUB_TOKEN else {}+ response = github_request(+ "GET",+ f"https://api.github.com/repos/PostHog/posthog/{path}",+ source="tasks_infrastructure_admin",+ priority=Priority.NORMAL,+ headers=headers,+ timeout=5,+ )+ response.raise_for_status()+ return cast(dict[str, JsonValue], response.json())++ def package(self) -> JsonValue:+ package = self._json("https://registry.npmjs.org/@posthog/agent/latest").json()+ return {"version": package["version"], "revision": package.get("gitHead")}++ def build_jobs(self, run_id: JsonValue) -> list[JsonValue]:+ response = self._github(f"actions/runs/{int(str(run_id))}/jobs?per_page=100")+ names = {+ "Build and push Tasks Sandbox container image": "Base images",+ "Build and push the derived sandbox images": "Derived images",+ }+ return [+ {+ "name": names[str(job["name"])],+ "status": job.get("status"),+ "conclusion": job.get("conclusion"),+ "promotion": next(+ (+ step.get("conclusion") or step.get("status")+ for step in cast(list[dict[str, JsonValue]], job.get("steps", []))+ if step.get("name") == "Promote the smoked base image to :master"+ ),+ None,+ ),+ }+ for job in cast(list[dict[str, JsonValue]], response["jobs"])+ if job.get("name") in names+ ]++ def release(self) -> JsonValue:+ content = self._github("contents/products/tasks/backend/sandbox/images/Dockerfile.sandbox-base?ref=master")+ dockerfile = base64.b64decode(str(content["content"])).decode()+ pin = re.search(r"^ARG AGENT_VERSION=(\S+)", dockerfile, re.MULTILINE)+ if pin is None:+ raise ValueError("Missing agent version")+ runs = self._github("actions/workflows/cd-sandbox-base-image.yml/runs?branch=master&event=push&per_page=5")+ return {+ "pin": pin.group(1),+ "runs": [+ {+ **{+ key: run.get(key)+ for key in ("id", "head_sha", "status", "conclusion", "html_url", "created_at")+ },+ "build_jobs": self.build_jobs(run["id"]),+ }+ for run in cast(list[dict[str, JsonValue]], runs["workflow_runs"])+ ],+ }++ def registry(self, name: str) -> JsonValue:+ repo = f"posthog/posthog-sandbox-{name}"+ token = self._json(f"https://ghcr.io/token?service=ghcr.io&scope=repository:{repo}:pull").json()["token"]+ headers = {+ "Authorization": f"Bearer {token}",+ "Accept": "application/vnd.oci.image.index.v1+json, application/vnd.oci.image.manifest.v1+json, application/vnd.docker.distribution.manifest.list.v2+json, application/vnd.docker.distribution.manifest.v2+json",+ }+ response = self._json(f"https://ghcr.io/v2/{repo}/manifests/master", headers=headers)+ digest = response.headers["Docker-Content-Digest"]+ platforms: list[JsonValue] = []+ for entry in response.json().get("manifests", []):+ arch = entry.get("platform", {}).get("architecture")+ if arch not in ("amd64", "arm64"):+ continue+ manifest = self._json(f"https://ghcr.io/v2/{repo}/manifests/{entry['digest']}", headers=headers).json()+ config = self._json(+ f"https://ghcr.io/v2/{repo}/blobs/{manifest['config']['digest']}", headers=headers+ ).json()+ labels = config.get("config", {}).get("Labels", {})+ platforms.append(+ {+ "arch": arch,+ "digest": entry["digest"],+ "version": labels.get("com.posthog.sandbox.agent-version"),+ "revision": labels.get("org.opencontainers.image.revision"),+ "base_revision": labels.get("com.posthog.sandbox.base-revision"),+ "inputs_digest": labels.get("com.posthog.sandbox.inputs-digest"),+ }+ )+ if {cast(dict[str, JsonValue], platform)["arch"] for platform in platforms} != {"amd64", "arm64"}:+ raise ValueError("Incomplete image platforms")+ return {"name": name, "reference": f"ghcr.io/{repo}@{digest}", "platforms": platforms}++ def custom_images(self) -> JsonValue:+ rows = list(+ SandboxCustomImage.objects.unscoped()+ .exclude(status=SandboxCustomImage.Status.ARCHIVED)+ .annotate(+ has_published_image=Case(+ When(modal_image_name="", then=Value(False)), default=Value(True), output_field=BooleanField()+ ),+ has_error=Case(When(error="", then=Value(False)), default=Value(True), output_field=BooleanField()),+ has_spec=Case(When(spec={}, then=Value(False)), default=Value(True), output_field=BooleanField()),+ )+ .order_by("id")+ .values(+ "id",+ "team_id",+ "status",+ "version",+ "base_image_reference",+ "base_image_refresh_reference",+ "has_published_image",+ "has_error",+ "has_spec",+ "updated_at",+ )[: MAX_IMAGES + 1]+ )+ images: list[JsonValue] = [+ CustomImageStatus(+ **{**row, "id": str(row["id"])}, workflow_url=workflow_url(f"build-sandbox-image-{row['id']}")+ ).model_dump(mode="json")+ for row in rows[:MAX_IMAGES]+ ]+ return {"images": images, "truncated": len(rows) > MAX_IMAGES, "limit": MAX_IMAGES}++ def dev_stack(self) -> JsonValue:+ reference = get_tasks_cache().get(f"tasks:dev-stack-image:baked-base-reference:{DEV_STACK_IMAGE_NAME}")+ return {+ "name": DEV_STACK_IMAGE_NAME,+ "base_image_reference": reference if isinstance(reference, str) else None,+ "workflow_url": workflow_url(f"bake-dev-stack-image-{DEV_STACK_IMAGE_NAME}"),+ }++ @async_to_sync+ async def workflow(self, workflow_id: str) -> JsonValue:+ client = await asyncio.wait_for(async_connect(), timeout=5)+ try:+ description = await client.get_workflow_handle(workflow_id).describe(rpc_timeout=timedelta(seconds=5))+ except RPCError as error:+ if error.status == RPCStatusCode.NOT_FOUND:+ return {"status": "not_found", "activities": [], "url": workflow_url(workflow_id)}+ raise+ return {+ "status": description.status.name.lower() if description.status else "unknown",+ "run_id": description.run_id,+ "started_at": description.start_time.isoformat() if description.start_time else None,+ "closed_at": description.close_time.isoformat() if description.close_time else None,+ "url": f"{workflow_url(workflow_id)}/{quote(description.run_id, safe='')}/history",+ "activities": [+ {+ "name": activity.activity_type.name,+ "state": PendingActivityState.Name(activity.state).removeprefix("PENDING_ACTIVITY_STATE_").lower(),+ "attempt": activity.attempt,+ }+ for activity in description.raw_description.pending_activities+ ],+ }++ def read(self, name: str, loader: Callable[[], JsonValue]) -> SourceSnapshot:+ cache = get_tasks_cache()+ key = f"tasks:infrastructure-admin:v1:{name}"+ cached = cache.get(key)+ previous = SourceSnapshot.model_validate_json(cached) if isinstance(cached, str) else None+ if (+ previous+ and previous.observed_at+ and timezone.now() - previous.observed_at < timedelta(seconds=CACHE_SECONDS)+ ):+ return previous+ lock = get_tasks_stream_redis_sync(use_dedicated=bool(settings.TASKS_REDIS_URL)).lock(+ f"{key}:lock", timeout=90, blocking=False+ )+ if not lock.acquire():+ return (+ previous.model_copy(update={"status": "refreshing"})+ if previous+ else SourceSnapshot(status="refreshing")+ )+ try:+ data = loader()+ if not lock.owned():+ return (+ previous.model_copy(update={"status": "refreshing"})+ if previous+ else SourceSnapshot(status="refreshing")+ )+ snapshot = SourceSnapshot(status="ok", observed_at=timezone.now(), data=data)+ cache.set(key, snapshot.model_dump_json(), timeout=3600)+ return snapshot+ except Exception:+ logger.exception("tasks_infrastructure_source_failed", extra={"source": name})+ return previous.model_copy(update={"status": "error"}) if previous else SourceSnapshot(status="error")+ finally:+ with suppress(LockNotOwnedError):+ lock.release()diff --git a/products/tasks/backend/presentation/views/infrastructure_admin.py b/products/tasks/backend/presentation/views/infrastructure_admin.pynew file mode 100644index 000000000000..71cae913145f--- /dev/null+++ b/products/tasks/backend/presentation/views/infrastructure_admin.py@@ -0,0 +1,50 @@+from collections.abc import Callable+from uuid import UUID++from django.conf import settings+from django.core.exceptions import PermissionDenied+from django.http import HttpRequest, HttpResponse, JsonResponse+from django.shortcuts import render+from django.views.decorators.http import require_GET++from loginas.utils import is_impersonated_session+from pydantic import JsonValue++from products.tasks.backend.facade.infrastructure import DEV_STACK_IMAGE_NAME, IMAGE_NAMES, InfrastructureStatus+++@require_GET+def infrastructure_admin(request: HttpRequest) -> HttpResponse:+ if not request.user.is_active or not request.user.is_staff or is_impersonated_session(request):+ raise PermissionDenied+ source = request.GET.get("source")+ if source is None:+ return render(+ request, "infrastructure_admin.html", {"js_url": settings.JS_URL, "region": settings.CLOUD_DEPLOYMENT}+ )+ collector = InfrastructureStatus()+ loaders: dict[str, Callable[[], JsonValue]] = {+ "package": collector.package,+ "release": collector.release,+ "custom": collector.custom_images,+ "dev_stack": collector.dev_stack,+ }+ if source in IMAGE_NAMES:+ loader = lambda: collector.registry(source)+ elif source == "workflow":+ image_id = request.GET.get("image_id", "")+ if image_id == "dev_stack":+ workflow_id = f"bake-dev-stack-image-{DEV_STACK_IMAGE_NAME}"+ else:+ try:+ parsed_id = UUID(image_id)+ except ValueError:+ return JsonResponse({"detail": "Invalid image ID"}, status=400)+ workflow_id = f"build-sandbox-image-{parsed_id}"+ source = f"workflow:{workflow_id}"+ loader = lambda: collector.workflow(workflow_id)+ elif source in loaders:+ loader = loaders[source]+ else:+ return JsonResponse({"detail": "Unknown source"}, status=400)+ return JsonResponse(collector.read(source, loader).model_dump(mode="json"))diff --git a/products/tasks/backend/templates/admin/tasks/task/change_list.html b/products/tasks/backend/templates/admin/tasks/task/change_list.htmlnew file mode 100644index 000000000000..cc10dfc79565--- /dev/null+++ b/products/tasks/backend/templates/admin/tasks/task/change_list.html@@ -0,0 +1,5 @@+{% extends "admin/change_list.html" %}+{% block object-tools-items %}+ <li><a href="{% url 'admin:tasks_infrastructure' %}">Agent release pipeline</a></li>+ {{ block.super }}+{% endblock %}diff --git a/products/tasks/backend/tests/test_infrastructure_admin.py b/products/tasks/backend/tests/test_infrastructure_admin.pynew file mode 100644index 000000000000..47fda0d8b6ac--- /dev/null+++ b/products/tasks/backend/tests/test_infrastructure_admin.py@@ -0,0 +1,198 @@+import base64+from datetime import timedelta++import time_machine+from posthog.test.base import BaseTest+from unittest.mock import Mock, patch++from django.contrib.sessions.backends.signed_cookies import SessionStore+from django.core.exceptions import PermissionDenied+from django.http import HttpResponse+from django.test import RequestFactory, SimpleTestCase, override_settings+from django.utils import timezone++import requests+import fakeredis+from parameterized import parameterized++from posthog.csp_middleware import CSPMiddleware+from posthog.models import User++from products.tasks.backend.logic.services.infrastructure_status import InfrastructureStatus, SourceSnapshot+from products.tasks.backend.models import SandboxCustomImage+from products.tasks.backend.presentation.views.infrastructure_admin import infrastructure_admin+from products.tasks.backend.redis import get_tasks_cache+++class TestInfrastructureAdminPermissions(SimpleTestCase):+ @parameterized.expand([(False, True, False), (True, False, False), (True, True, True)])+ def test_denies_non_staff_inactive_and_impersonated_users(+ self, staff: bool, active: bool, impersonated: bool+ ) -> None:+ request = RequestFactory().get("/admin/tasks/task/infrastructure/", {"source": "custom"})+ request.user = User(is_staff=staff, is_active=active)+ request.session = SessionStore()+ if impersonated:+ request.session["loginas_from_user"] = "original-user"+ with self.assertRaises(PermissionDenied):+ infrastructure_admin(request)+++@override_settings(TASKS_REDIS_URL="", CACHES={"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}})+class TestInfrastructureSourceCache(SimpleTestCase):+ def setUp(self) -> None:+ get_tasks_cache().clear()+ self.redis = fakeredis.FakeRedis()+ redis_client = patch(+ "products.tasks.backend.logic.services.infrastructure_status.get_tasks_stream_redis_sync",+ return_value=self.redis,+ )+ redis_client.start()+ self.addCleanup(redis_client.stop)++ def test_expired_refresh_does_not_publish_or_release_the_next_owners_lock(self) -> None:+ cache = get_tasks_cache()+ key = "tasks:infrastructure-admin:v1:package"+ successor = self.redis.lock(f"{key}:lock", timeout=90, blocking=False)+ newer = SourceSnapshot(status="ok", observed_at=timezone.now(), data={"version": "2.0.0"})++ def response(*args: object, **kwargs: object) -> Mock:+ self.redis.pexpire(f"{key}:lock", 0)+ self.assertTrue(successor.acquire())+ cache.set(key, newer.model_dump_json())+ return Mock(json=lambda: {"version": "1.0.0"})++ collector = InfrastructureStatus()+ with patch("requests.get", side_effect=response):+ result = collector.read("package", collector.package)+ self.assertEqual(result.status, "refreshing")+ self.assertTrue(successor.owned())+ self.assertEqual(collector.read("package", collector.package), newer)++ @parameterized.expand(+ [("completed", "skipped"), ("completed", "failure"), ("queued", None), ("completed", "success")]+ )+ def test_workflow_success_does_not_hide_build_job_results(self, status: str, conclusion: str | None) -> None:+ responses = [+ Mock(json=lambda: {"content": base64.b64encode(b"ARG AGENT_VERSION=1.0.0").decode()}),+ Mock(json=lambda: {"workflow_runs": [{"id": 1, "status": "completed", "conclusion": "success"}]}),+ Mock(+ json=lambda: {+ "jobs": [+ {+ "name": "Determine if sandbox image needs to be built",+ "status": "completed",+ "conclusion": "success",+ },+ {+ "name": "Build and push Tasks Sandbox container image",+ "status": status,+ "conclusion": conclusion,+ "steps": [+ {+ "name": "Promote the smoked base image to :master",+ "status": "completed",+ "conclusion": "skipped",+ }+ ],+ },+ {+ "name": "Build and push the derived sandbox images",+ "status": status,+ "conclusion": conclusion,+ },+ ]+ }+ ),+ ]+ collector = InfrastructureStatus()+ with patch("products.tasks.backend.logic.services.infrastructure_status.github_request", side_effect=responses):+ result = collector.read("release", collector.release).model_dump(mode="json")+ self.assertEqual(result["status"], "ok")+ self.assertEqual(+ result["data"]["runs"][0]["build_jobs"],+ [+ {"name": "Base images", "status": status, "conclusion": conclusion, "promotion": "skipped"},+ {"name": "Derived images", "status": status, "conclusion": conclusion, "promotion": None},+ ],+ )++ def test_failed_refresh_preserves_evidence_without_claiming_freshness(self) -> None:+ collector = InfrastructureStatus()+ now = timezone.now()+ with (+ time_machine.travel(now, tick=False),+ patch("requests.get", return_value=Mock(json=lambda: {"version": "1.0.0"})),+ ):+ first = collector.read("package", collector.package)+ self.assertEqual(first.status, "ok")+ with (+ time_machine.travel(now + timedelta(minutes=2), tick=False),+ patch("requests.get", side_effect=requests.Timeout),+ ):+ stale = collector.read("package", collector.package)+ self.assertEqual(stale.status, "error")+ self.assertEqual(stale.data, first.data)+ self.assertEqual(stale.observed_at, first.observed_at)++ def test_partial_registry_publication_is_not_healthy(self) -> None:+ responses = [+ Mock(json=lambda: {"token": "test-token"}),+ Mock(headers={"Docker-Content-Digest": "sha256:test"}, json=lambda: {"manifests": []}),+ ]+ collector = InfrastructureStatus()+ with patch("requests.get", side_effect=responses):+ result = collector.read("vm", lambda: collector.registry("vm"))+ self.assertEqual(result.status, "error")+ self.assertIsNone(result.data)+++@override_settings(TASKS_REDIS_URL="", CACHES={"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}})+class TestInfrastructureInventory(BaseTest):+ def test_staff_inventory_contains_lineage_without_private_build_content(self) -> None:+ get_tasks_cache().clear()+ self.user.is_staff = True+ self.user.save()+ self.client.force_login(self.user)+ image = SandboxCustomImage.objects.for_team(self.team.id).create(+ team=self.team,+ name="Private test image",+ spec={"packages": ["example-package"]},+ status="ready",+ version=3,+ modal_image_name="test-image:v3",+ base_image_reference="ghcr.io/posthog/posthog-sandbox-vm@sha256:old",+ base_image_refresh_reference=None,+ error="private build failure detail",+ build_log="private build output",+ )+ SandboxCustomImage.objects.for_team(self.team.id).create(team=self.team, name="Archived", status="archived")+ response = self.client.get("/admin/tasks/task/infrastructure/", {"source": "custom"})+ self.assertEqual(response.status_code, 200)+ rows = response.json()["data"]["images"]+ self.assertEqual(len(rows), 1)+ self.assertEqual(rows[0]["id"], str(image.id))+ self.assertEqual(rows[0]["base_image_reference"], image.base_image_reference)+ self.assertTrue(rows[0]["has_error"])+ self.assertTrue(rows[0]["has_published_image"])+ for private_value in (+ "Private test image",+ "private build failure detail",+ "private build output",+ "example-package",+ ):+ self.assertNotIn(private_value, response.content.decode())+ self.assertIn("no-cache", response["Cache-Control"])+ self.assertEqual(self.client.post("/admin/tasks/task/infrastructure/", {"source": "custom"}).status_code, 405)+++@override_settings(ADMIN_PORTAL_ENABLED=True, JS_URL="https://assets.example.com", DEBUG=False)+class TestInfrastructureAdminCSP(SimpleTestCase):+ @parameterized.expand([("/admin/tasks/task/infrastructure/", True), ("/admin/", False)])+ def test_bundle_origin_is_limited_to_infrastructure_page(self, path: str, allowed: bool) -> None:+ request = RequestFactory().get(path)+ response = CSPMiddleware(lambda _: HttpResponse("page"))(request)+ directives = dict(part.split(" ", 1) for part in response["Content-Security-Policy"].split("; "))+ self.assertEqual("https://assets.example.com" in directives["script-src"], allowed)+ self.assertEqual("https://assets.example.com" in directives["style-src"], allowed)+ self.assertEqual(directives["frame-ancestors"], "'none'")diff --git a/products/tasks/frontend/infrastructure/CustomImageInventory.tsx b/products/tasks/frontend/infrastructure/CustomImageInventory.tsxnew file mode 100644index 000000000000..5be3e27b3e80--- /dev/null+++ b/products/tasks/frontend/infrastructure/CustomImageInventory.tsx@@ -0,0 +1,119 @@+import { Badge, Button, Card, Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@posthog/quill'++import { Sources, customState, fresh, labels, variants } from './infrastructureTypes'++export function CustomImageInventory({+ sources,+ onInspect,+ inspecting,+}: {+ sources: Sources+ onInspect: (id: string) => void+ inspecting?: string | null+}): JSX.Element {+ const data = sources.custom?.data+ const base = fresh(sources.vm) ? sources.vm?.data?.reference : undefined+ return (+ <Card className="inventory">+ <div className="section-title">+ <div>+ <h2>Custom image fan-out</h2>+ <p className="muted">Automatic refresh checks run every 10 minutes, up to 10 images per sweep.</p>+ </div>+ </div>+ {!data ? (+ <p className="empty-state">+ {sources.custom?.status === 'error'+ ? 'Inventory unavailable. Refresh to retry.'+ : 'Loading custom images…'}+ </p>+ ) : (+ <>+ {(!fresh(sources.custom) || !base) && (+ <p className="alert">+ Freshness is unverified until both inventory and the VM registry are available.+ </p>+ )}+ {data.truncated && (+ <p className="alert">+ Showing the first {data.limit} images. This is a partial inventory; fleet completion is+ unverified.+ </p>+ )}+ {data.images.length === 0 ? (+ <p className="empty-state">No active custom images in this region.</p>+ ) : (+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead>Image / project</TableHead>+ <TableHead>Published</TableHead>+ <TableHead>Refresh</TableHead>+ <TableHead>Base → target</TableHead>+ <TableHead>Evidence</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {data.images.map((image) => {+ const state = fresh(sources.custom) ? customState(image, base) : 'unknown'+ const staleServing =+ fresh(sources.custom) &&+ image.status === 'ready' &&+ image.has_published_image &&+ !!base &&+ image.base_image_reference !== base+ return (+ <TableRow key={image.id}>+ <TableCell>+ <code title={image.id}>{image.id.slice(0, 8)}</code>+ <div className="muted">Project {image.team_id}</div>+ </TableCell>+ <TableCell>+ <span>{image.has_published_image ? `v${image.version}` : 'None'}</span>+ <div className="muted">+ {staleServing ? 'Serving older base' : image.status}+ </div>+ </TableCell>+ <TableCell>+ <Badge variant={variants[state]}>+ {state === 'failed' && staleServing+ ? 'Refresh failed'+ : labels[state]}+ </Badge>+ </TableCell>+ <TableCell className="digest">+ <code title={image.base_image_reference || ''}>+ {image.base_image_reference?.split('@')[1]?.slice(0, 19) ||+ 'Unrecorded'}+ </code>+ <div>+ <code title={image.base_image_refresh_reference || ''}>+ {image.base_image_refresh_reference+ ? `→ ${image.base_image_refresh_reference.split('@')[1]?.slice(0, 19)}`+ : 'No pending target'}+ </code>+ </div>+ </TableCell>+ <TableCell>+ <Button+ variant="outline"+ size="sm"+ disabled={!!inspecting}+ loading={inspecting === image.id}+ onClick={() => onInspect(image.id)}+ data-attr="infra-inspect-image"+ >+ Inspect+ </Button>+ </TableCell>+ </TableRow>+ )+ })}+ </TableBody>+ </Table>+ )}+ </>+ )}+ </Card>+ )+}diff --git a/products/tasks/frontend/infrastructure/InfrastructureAdmin.tsx b/products/tasks/frontend/infrastructure/InfrastructureAdmin.tsxnew file mode 100644index 000000000000..b1a5b7580e2a--- /dev/null+++ b/products/tasks/frontend/infrastructure/InfrastructureAdmin.tsx@@ -0,0 +1,160 @@+import { useActions, useValues } from 'kea'++import { Badge, Button, Card } from '@posthog/quill'++import { CustomImageInventory } from './CustomImageInventory'+import { infrastructureLogic } from './infrastructureLogic'+import { fresh, imageNames, imageState, sourceNames } from './infrastructureTypes'+import { ReleasePipeline } from './ReleasePipeline'+import { StageInspector } from './StageInspector'++export function InfrastructureAdmin({ region }: { region: string }): JSX.Element {+ const { sources, sourcesLoading, paused, workflow, workflowLoading, now, selected, showSources } =+ useValues(infrastructureLogic)+ const { loadSources, setPaused, loadWorkflow, setSelected, setShowSources } = useActions(infrastructureLogic)+ const data = sources || {}+ const connected = sourceNames.filter((name) => fresh(data[name], now)).length+ const current = imageNames.filter((name) => imageState(data, name) === 'current').length+ return (+ <div className="app-shell">+ <header className="app-header">+ <a className="brand" href="/admin/">+ <span>PostHog</span>+ <span className="muted">/ agent infrastructure</span>+ </a>+ <div className="header-right">+ <Badge>{region}</Badge>+ <span className="muted">Read-only</span>+ <a href="/admin/">Django admin ↗</a>+ </div>+ </header>+ <div className="page-heading">+ <div>+ <span className="eyebrow">Agent infrastructure</span>+ <h1>Agent release pipeline</h1>+ <p>Follow the published package into sandbox images and regional custom builds.</p>+ </div>+ <div className="refresh-controls">+ <span className="muted">{paused ? 'Refresh paused' : 'Refreshes every minute'}</span>+ <Button variant="outline" onClick={() => setPaused(!paused)} data-attr="infra-pause">+ {paused ? 'Resume' : 'Pause'}+ </Button>+ <Button+ variant="outline"+ loading={sourcesLoading}+ onClick={() => loadSources()}+ data-attr="infra-refresh"+ >+ Refresh+ </Button>+ </div>+ </div>+ {sources && connected !== sourceNames.length && (+ <p className="alert">+ Some sources are unavailable or stale. Their rollout state is unverified; inspect Data sources for+ timestamps.+ </p>+ )}+ <div className="summary-grid">+ <Card className="summary">+ <span className="muted">npm latest</span>+ <strong>{data.package?.data?.version || '…'}</strong>+ <span className="muted">Published package</span>+ </Card>+ <Card className="summary">+ <span className="muted">Master pin</span>+ <strong>{data.release?.data?.pin || '…'}</strong>+ <span className="muted">Target agent version</span>+ </Card>+ <Card className="summary">+ <span className="muted">Registry coverage</span>+ <strong>+ {current}+ <small> / 6 images</small>+ </strong>+ <span className="muted">Version and lineage on both platforms</span>+ </Card>+ <Card className="summary">+ <span className="muted">Fresh sources</span>+ <strong>+ {connected}+ <small> / {sourceNames.length}</small>+ </strong>+ <span className="muted">Registry, GitHub, npm, Postgres and Redis</span>+ </Card>+ </div>+ <nav className="tabs">+ <Button+ variant={!showSources ? 'secondary' : 'outline'}+ onClick={() => setShowSources(false)}+ data-attr="infra-pipeline-tab"+ >+ Pipeline+ </Button>+ <Button+ variant={showSources ? 'secondary' : 'outline'}+ onClick={() => setShowSources(true)}+ data-attr="infra-sources-tab"+ >+ Data sources+ </Button>+ </nav>+ {showSources ? (+ <Card className="sources-panel">+ <div className="section-title">+ <h2>Source freshness</h2>+ </div>+ {sourceNames.map((name) => (+ <div key={name} className="source-row">+ <strong>{name.replace('_', ' ')}</strong>+ <span className="muted">+ {data[name]?.observed_at+ ? new Date(data[name]!.observed_at!).toISOString()+ : 'Not observed'}+ </span>+ <Badge variant={fresh(data[name], now) ? 'success' : 'warning'}>+ {fresh(data[name], now)+ ? 'Fresh'+ : data[name]?.status === 'ok'+ ? 'Stale'+ : data[name]?.status || 'Loading'}+ </Badge>+ </div>+ ))}+ </Card>+ ) : (+ <div className="workspace">+ <div className="workspace-main">+ <ReleasePipeline sources={data} selected={selected} onSelect={setSelected} />+ </div>+ <aside id="stage-inspector">+ <StageInspector+ selected={selected}+ sources={data}+ workflow={workflow}+ workflowLoading={workflowLoading}+ onWorkflow={(id) => loadWorkflow({ id })}+ />+ </aside>+ <div className="workspace-inventory">+ <CustomImageInventory+ sources={data}+ inspecting={workflowLoading ? selected : null}+ onInspect={(id) => {+ setSelected(id)+ loadWorkflow({ id })+ document.getElementById('stage-inspector')?.scrollIntoView({ block: 'nearest' })+ }}+ />+ </div>+ </div>+ )}+ <footer className="page-footer">+ <span>Agent infrastructure · timestamps in UTC</span>+ <span>+ Current inventory; historical rollout completion and running sandbox versions are not recorded here.+ </span>+ </footer>+ </div>+ )+}diff --git a/products/tasks/frontend/infrastructure/PipelineNode.tsx b/products/tasks/frontend/infrastructure/PipelineNode.tsxnew file mode 100644index 000000000000..fa7e6491911c--- /dev/null+++ b/products/tasks/frontend/infrastructure/PipelineNode.tsx@@ -0,0 +1,34 @@+import { Badge, Card } from '@posthog/quill'++import { Evidence, labels, variants } from './infrastructureTypes'++export function PipelineNode({+ id,+ title,+ subtitle,+ state,+ selected,+ onSelect,+}: {+ id: string+ title: string+ subtitle: string+ state: Evidence+ selected: string+ onSelect: (id: string) => void+}): JSX.Element {+ return (+ <Card className={`pipeline-node node-${id} ${selected === id ? 'selected' : ''}`}>+ <button+ className="node-button"+ aria-pressed={selected === id}+ onClick={() => onSelect(id)}+ data-attr={`infra-stage-${id}`}+ >+ <strong>{title}</strong>+ <span className="node-subtitle">{subtitle}</span>+ <Badge variant={variants[state]}>{labels[state]}</Badge>+ </button>+ </Card>+ )+}diff --git a/products/tasks/frontend/infrastructure/ReleasePipeline.stories.tsx b/products/tasks/frontend/infrastructure/ReleasePipeline.stories.tsxnew file mode 100644index 000000000000..92d510144d66--- /dev/null+++ b/products/tasks/frontend/infrastructure/ReleasePipeline.stories.tsx@@ -0,0 +1,104 @@+import './infrastructureAdmin.css'++import type { Meta, StoryObj } from '@storybook/react'++import { ThemeProvider } from '@posthog/quill'++import { CustomImageInventory } from './CustomImageInventory'+import { Sources, imageNames } from './infrastructureTypes'+import { ReleasePipeline } from './ReleasePipeline'++function exampleSources(): Sources {+ const observed_at = new Date().toISOString()+ const sources: Sources = {+ package: { status: 'ok', observed_at, data: { version: '1.0.0', revision: 'example-revision' } },+ release: { status: 'ok', observed_at, data: { pin: '1.0.0', runs: [] } },+ custom: { status: 'ok', observed_at, data: { images: [], truncated: false, limit: 1000 } },+ dev_stack: {+ status: 'ok',+ observed_at,+ data: {+ name: 'posthog-dev-stack',+ base_image_reference: 'ghcr.io/posthog/posthog-sandbox-vm@sha256:example',+ workflow_url: 'https://example.com/workflow',+ },+ },+ }+ for (const name of imageNames) {+ sources[name] = {+ status: 'ok',+ observed_at,+ data: {+ name,+ reference: `ghcr.io/posthog/posthog-sandbox-${name}@sha256:example`,+ platforms: ['amd64', 'arm64'].map((arch) => ({+ arch,+ version: '1.0.0',+ revision: 'example-revision',+ base_revision: 'example-revision',+ inputs_digest: 'example-inputs',+ digest: 'sha256:example',+ })),+ },+ }+ }+ sources.custom!.data!.images = ['ready', 'building', 'ready'].map((status, index) => ({+ id: `${index + 1}0000000-0000-4000-8000-000000000001`,+ team_id: 1,+ status,+ version: 2,+ base_image_reference:+ index === 0 ? sources.vm!.data!.reference : 'ghcr.io/posthog/posthog-sandbox-vm@sha256:previous',+ base_image_refresh_reference: index === 1 ? sources.vm!.data!.reference : null,+ has_error: index === 2,+ has_published_image: true,+ has_spec: true,+ updated_at: observed_at,+ workflow_url: 'https://example.com/workflow',+ }))+ return sources+}++const meta: Meta<typeof ReleasePipeline> = {+ title: 'Products/Tasks/Infrastructure admin',+ component: ReleasePipeline,+ parameters: { layout: 'fullscreen' },+ decorators: [+ (Story) => (+ <ThemeProvider defaultTheme="light">+ <div className="app-shell">+ <Story />+ </div>+ </ThemeProvider>+ ),+ ],+}+export default meta+export const RollingOut: StoryObj<typeof ReleasePipeline> = {+ render: () => {+ const sources = exampleSources()+ return (+ <div className="workspace-main">+ <ReleasePipeline sources={sources} selected="custom" onSelect={() => {}} />+ <CustomImageInventory sources={sources} onInspect={() => {}} />+ </div>+ )+ },+}+export const Unavailable: StoryObj<typeof ReleasePipeline> = {+ args: { sources: {}, selected: 'custom', onSelect: () => {} },+}+export const AwaitingPin: StoryObj<typeof ReleasePipeline> = {+ render: () => {+ const sources = exampleSources()+ sources.package!.data!.version = '1.1.0'+ return <ReleasePipeline sources={sources} selected="release" onSelect={() => {}} />+ },+}+export const Narrow: StoryObj<typeof ReleasePipeline> = {+ render: () => (+ <div className="workspace-main w-130">+ <ReleasePipeline sources={exampleSources()} selected="custom" onSelect={() => {}} />+ </div>+ ),+}diff --git a/products/tasks/frontend/infrastructure/ReleasePipeline.tsx b/products/tasks/frontend/infrastructure/ReleasePipeline.tsxnew file mode 100644index 000000000000..0fdf50909ad9--- /dev/null+++ b/products/tasks/frontend/infrastructure/ReleasePipeline.tsx@@ -0,0 +1,141 @@+import { Card } from '@posthog/quill'++import { Sources, customState, fresh, imageNames, imageState, pinState } from './infrastructureTypes'+import { PipelineNode } from './PipelineNode'++export function ReleasePipeline({+ sources,+ selected,+ onSelect,+}: {+ sources: Sources+ selected: string+ onSelect: (id: string) => void+}): JSX.Element {+ const base = fresh(sources.vm) ? sources.vm?.data?.reference : undefined+ const custom = sources.custom?.data+ const eligible = custom?.images.filter((image) => image.has_published_image && image.has_spec) || []+ const customCurrent = eligible.filter((image) => customState(image, base) === 'current').length+ const customFresh = fresh(sources.custom) && !!base && !custom?.truncated+ const devStack = sources.dev_stack?.data+ return (+ <Card className="pipeline-panel">+ <div className="section-title">+ <div>+ <h2>Package → image → task</h2>+ <p className="muted">+ Current master tags, then regional image refreshes. Select a stage for evidence.+ </p>+ </div>+ </div>+ <div className="pipeline-wrap">+ <div className="pipeline-stage-labels">+ <span>01 Release and pin</span>+ <span>02 Base image</span>+ <span>03 Derived images</span>+ <span>04 Regional fan-out</span>+ </div>+ <div className="pipeline">+ <svg className="connections" viewBox="0 0 1040 540" preserveAspectRatio="none" aria-hidden="true">+ <defs>+ <marker+ id="infra-arrow"+ viewBox="0 0 8 8"+ refX="7"+ refY="4"+ markerWidth="5"+ markerHeight="5"+ orient="auto-start-reverse"+ >+ <path d="M1 1 L7 4 L1 7" fill="none" stroke="currentColor" />+ </marker>+ </defs>+ <path d="M126 145 V212 M236 262 H278 M498 262 H518 V147 H540 M498 262 H540 M498 262 H518 V377 H540 M760 377 H780 V322 H802 M760 377 H780 V442 H802" />+ <path className="sibling-path" d="M126 312 V437 M126 339 H260 V487 H278" />+ <text x="130" y="180">+ version bump merged+ </text>+ <text x="783" y="256">+ VM digest changes+ </text>+ </svg>+ <PipelineNode+ id="package"+ title="Agent package"+ subtitle={sources.package?.data?.version || 'Reading npm'}+ state={fresh(sources.package) ? 'current' : 'unknown'}+ selected={selected}+ onSelect={onSelect}+ />+ <PipelineNode+ id="release"+ title="Sandbox version pin"+ subtitle={sources.release?.data?.pin || 'Reading master'}+ state={pinState(sources)}+ selected={selected}+ onSelect={onSelect}+ />+ {imageNames.map((name) => (+ <PipelineNode+ key={name}+ id={name}+ title={+ {+ base: 'Sandbox base',+ notebook: 'Notebook',+ streamlit: 'Streamlit',+ pi: 'Pi',+ autoresearch: 'Autoresearch',+ vm: 'VM base',+ }[name]+ }+ subtitle={+ [...new Set(sources[name]?.data?.platforms.map((p) => p.version || '?'))].join(' / ') ||+ 'Reading registry'+ }+ state={imageState(sources, name)}+ selected={selected}+ onSelect={onSelect}+ />+ ))}+ <PipelineNode+ id="custom"+ title="Custom images"+ subtitle={+ custom ? `${customCurrent} / ${eligible.length} eligible current` : 'Reading inventory'+ }+ state={+ !customFresh || eligible.length === 0+ ? 'unknown'+ : eligible.some((image) => customState(image, base) === 'failed')+ ? 'failed'+ : customCurrent === eligible.length+ ? 'current'+ : 'waiting'+ }+ selected={selected}+ onSelect={onSelect}+ />+ <PipelineNode+ id="dev_stack"+ title="PostHog dev stack"+ subtitle={devStack?.name || 'Reading bake record'}+ state={+ !fresh(sources.dev_stack) || !base || !devStack?.base_image_reference+ ? 'unknown'+ : devStack.base_image_reference === base+ ? 'current'+ : 'waiting'+ }+ selected={selected}+ onSelect={onSelect}+ />+ <span className="parallel-caption">Notebook and Streamlit build alongside the base.</span>+ </div>+ <div className="pipeline-legend">+ Current means the version and available lineage match. Running sandboxes are outside this view.+ </div>+ </div>+ </Card>+ )+}diff --git a/products/tasks/frontend/infrastructure/StageInspector.tsx b/products/tasks/frontend/infrastructure/StageInspector.tsxnew file mode 100644index 000000000000..0bc09d169167--- /dev/null+++ b/products/tasks/frontend/infrastructure/StageInspector.tsx@@ -0,0 +1,180 @@+import { Badge, Button, Card } from '@posthog/quill'++import { ImageName, Source, Sources, Workflow, fresh, imageNames } from './infrastructureTypes'++export function StageInspector({+ selected,+ sources,+ workflow,+ workflowLoading,+ onWorkflow,+}: {+ selected: string+ sources: Sources+ workflow: { id: string; source: Source<Workflow> } | null+ workflowLoading: boolean+ onWorkflow: (id: string) => void+}): JSX.Element {+ const source = sources[selected as keyof Sources]+ const image = sources.custom?.data?.images.find((item) => item.id === selected)+ const registry = imageNames.includes(selected as ImageName) ? sources[selected as ImageName]?.data : null+ const run = workflow?.id === selected ? workflow.source : null+ return (+ <Card className="inspector">+ <div className="inspector-header">+ <span className="eyebrow">Stage evidence</span>+ <Badge variant={fresh(source) ? 'success' : 'default'}>+ {fresh(source) ? 'Observed' : image ? 'Custom image' : 'Unverified'}+ </Badge>+ </div>+ <h2>{image ? `Image ${image.id.slice(0, 8)}` : selected.replace('_', ' ')}</h2>+ {source?.observed_at && (+ <p className="muted">+ Observed {new Date(source.observed_at).toISOString().replace('T', ' ').slice(0, 19)} UTC+ </p>+ )}+ {source?.status === 'error' && (+ <p className="alert">Source unavailable. Any values below are from the last successful read.</p>+ )}+ {selected === 'package' && (+ <p>Latest published npm version. A newer package does not mean the sandbox version pin has merged.</p>+ )}+ {selected === 'release' && (+ <>+ <p>+ Master's sandbox version pin and the latest five workflow runs. Unrelated changes can skip image+ builds. Build and promotion results below do not prove custom-image adoption.+ </p>+ {sources.release?.data?.runs.map((item) => (+ <div className="platform-details" key={item.id}>+ <a className="run-link" href={item.html_url} target="_blank" rel="noreferrer">+ <code>{item.head_sha.slice(0, 8)}</code>+ <span>{`Workflow ${item.conclusion || item.status} ↗`}</span>+ </a>+ {!item.build_jobs?.length && <p>Build jobs not observed.</p>}+ {item.build_jobs?.map((job) => (+ <div key={job.name}>+ <p>{`${job.name}: ${job.conclusion || job.status}`}</p>+ {job.promotion && <p>{`Base promotion: ${job.promotion}`}</p>}+ </div>+ ))}+ </div>+ ))}+ </>+ )}+ {registry && (+ <>+ <p className="digest">+ <code>{registry.reference}</code>+ </p>+ {registry.platforms.map((platform) => (+ <div className="platform-details" key={platform.arch}>+ <h3>{platform.arch}</h3>+ <dl>+ <dt>Agent</dt>+ <dd>{platform.version || 'Unrecorded'}</dd>+ <dt>Revision</dt>+ <dd>+ <code>{platform.revision || 'Unrecorded'}</code>+ </dd>+ <dt>Base revision</dt>+ <dd>+ <code>{platform.base_revision || 'Unrecorded'}</code>+ </dd>+ <dt>Inputs digest</dt>+ <dd>+ <code>{platform.inputs_digest || 'Unrecorded'}</code>+ </dd>+ </dl>+ </div>+ ))}+ </>+ )}+ {selected === 'custom' && (+ <>+ <p>+ Each image below shows its last successful base, pending refresh target and latest build state.+ </p>+ <p>+ A failed refresh can leave the image ready on its previous base. Images without a published+ version or a build spec are not eligible for automatic refresh.+ </p>+ <p>Choose Inspect on an image to read the latest Temporal execution.</p>+ </>+ )}+ {selected === 'dev_stack' && (+ <>+ <p>+ The recorded base of the last successful dev-stack bake. Missing records do not prove a failed+ bake.+ </p>+ <p className="digest">+ <code>{sources.dev_stack?.data?.base_image_reference || 'No recorded base'}</code>+ </p>+ <p>+ Base changes are checked every 2 minutes; the scheduled bake runs daily at 06:45 UTC when+ enabled.+ </p>+ </>+ )}+ {image && (+ <>+ <dl>+ <dt>Project</dt>+ <dd>{image.team_id}</dd>+ <dt>Image status</dt>+ <dd>{image.status}</dd>+ <dt>Published version</dt>+ <dd>{image.version}</dd>+ <dt>Last error</dt>+ <dd>{image.has_error ? 'Recorded' : 'None recorded'}</dd>+ </dl>+ <h3>Successful base</h3>+ <code className="digest">{image.base_image_reference || 'Unrecorded'}</code>+ <h3>Pending target</h3>+ <code className="digest">{image.base_image_refresh_reference || 'None recorded'}</code>+ </>+ )}+ {(image || selected === 'dev_stack') && (+ <>+ <Button+ variant="outline"+ loading={workflowLoading}+ onClick={() => onWorkflow(selected)}+ data-attr="infra-read-workflow"+ >+ Read latest build+ </Button>+ {run && (+ <>+ <h3>Latest Temporal execution</h3>+ <p>+ {!fresh(run)+ ? 'Temporal evidence is unavailable or stale. Read the latest build to update it.'+ : run.data?.status === 'not_found'+ ? 'No retained execution found.'+ : run.data?.status}+ </p>+ {run.observed_at && <p>Observed {new Date(run.observed_at).toISOString()}</p>}+ {run.data?.started_at && <p>Started {new Date(run.data.started_at).toISOString()}</p>}+ {run.data?.activities.map((activity) => (+ <p key={activity.name}>+ <code>{activity.name}</code>+ <span>{` · ${activity.state} · attempt ${activity.attempt}`}</span>+ </p>+ ))}+ </>+ )}+ <a+ href={run?.data?.url || image?.workflow_url || sources.dev_stack?.data?.workflow_url}+ target="_blank"+ rel="noreferrer"+ >+ Open Temporal history ↗+ </a>+ <p>Workflow IDs are reused. This is the latest execution, which may target an earlier base.</p>+ </>+ )}+ </Card>+ )+}diff --git a/products/tasks/frontend/infrastructure/infrastructureAdmin.css b/products/tasks/frontend/infrastructure/infrastructureAdmin.cssnew file mode 100644index 000000000000..ebb73f5d8971--- /dev/null+++ b/products/tasks/frontend/infrastructure/infrastructureAdmin.css@@ -0,0 +1,519 @@+@import 'tailwindcss' source(none);+@import '../../node_modules/@posthog/quill/dist/tokens.css';+@import '../../node_modules/@posthog/quill/dist/base.css';+@import '../../node_modules/@posthog/quill/dist/primitives.css';+@import '../../node_modules/@posthog/quill/dist/tailwind.css';+@source '.';++body {+ margin: 0;+ font-family: system-ui, sans-serif;+ font-size: 13px;+ color: var(--foreground);+ background: var(--background);+}++.app-shell {+ max-width: 1680px;+ padding: 0 32px;+ margin: auto;+ container-type: inline-size;+}++.app-shell h1,+.app-shell h2,+.app-shell h3,+.app-shell p {+ margin: 0;+}++.app-shell h1 {+ font-size: 28px;+ font-weight: 650;+ letter-spacing: -0.8px;+}++.app-shell h2 {+ font-size: 15px;+ font-weight: 600;+}++.app-shell h3 {+ font-size: 12px;+ font-weight: 600;+}++.app-shell a:hover {+ text-decoration: underline;+}++.app-shell code {+ font-size: 11px;+}++.app-header {+ display: flex;+ flex-wrap: wrap;+ gap: 16px;+ align-items: center;+ justify-content: space-between;+ min-height: 76px;+ border-bottom: 1px solid var(--border);+}++.brand,+.header-right,+.refresh-controls {+ display: flex;+ flex-wrap: wrap;+ gap: 12px;+ align-items: center;+}++.brand {+ font-size: 16px;+ font-weight: 650;+}++.muted {+ font-size: 12px;+ color: var(--muted-foreground);+}++.eyebrow {+ font-size: 10px;+ color: var(--muted-foreground);+ text-transform: uppercase;+ letter-spacing: 1px;+}++.page-heading {+ display: flex;+ flex-wrap: wrap;+ gap: 24px;+ align-items: center;+ justify-content: space-between;+ padding: 30px 0 24px;+}++.page-heading p {+ margin-top: 8px;+ color: var(--muted-foreground);+}++.summary-grid {+ display: grid;+ grid-template-columns: repeat(4, minmax(0, 1fr));+ gap: 12px;+ margin-bottom: 20px;+}++.summary {+ gap: 6px;+ padding: 18px 20px;+}++.summary strong {+ font-size: 25px;+ font-weight: 600;+}++.summary small {+ font-size: 12px;+ font-weight: 400;+ color: var(--muted-foreground);+}++.tabs {+ display: flex;+ gap: 8px;+ padding-bottom: 16px;+}++.workspace {+ display: grid;+ grid-template-areas: 'pipeline inspector' 'inventory inspector';+ grid-template-columns: minmax(0, 1fr) 290px;+ gap: 20px;+ align-items: start;+}++.workspace-main {+ display: grid;+ grid-area: pipeline;+ gap: 20px;+ min-width: 0;+ container-type: inline-size;+}++.workspace-inventory {+ grid-area: inventory;+ min-width: 0;+ container-type: inline-size;+}++#stage-inspector {+ grid-area: inspector;+ min-width: 0;+}++.pipeline-panel,+.inventory {+ gap: 0;+ padding: 0;+ overflow: hidden;+}++.section-title {+ padding: 18px 20px;+}++.section-title p {+ margin-top: 4px;+}++.pipeline-wrap {+ border-top: 1px solid var(--border);+}++.pipeline-stage-labels {+ display: grid;+ grid-template-columns: repeat(4, 1fr);+ gap: 12px;+ padding: 18px 16px 0;+ font-size: 10px;+ color: var(--muted-foreground);+}++.pipeline {+ position: relative;+ height: 555px;+ margin-top: 4px;+}++.connections {+ position: absolute;+ inset: 0;+ width: 100%;+ height: 540px;+ color: var(--muted-foreground);+}++.connections > path {+ fill: none;+ stroke: currentColor;+ stroke-opacity: 0.5;+ stroke-width: 1.3;+ marker-end: url('#infra-arrow');+}++.connections .sibling-path {+ stroke-dasharray: 4 4;+}++.connections text {+ font-size: 8px;+ fill: currentColor;+}++.pipeline-node {+ position: absolute;+ z-index: 1;+ gap: 0;+ width: 21.15%;+ padding: 0;+ overflow: hidden;+}++.pipeline-node.selected {+ outline: 1px solid var(--foreground);+}++.node-button {+ display: flex;+ flex-direction: column;+ gap: 8px;+ align-items: start;+ width: 100%;+ min-height: 100px;+ padding: 12px 10px;+ text-align: left;+ cursor: pointer;+}++.node-button:hover {+ background: var(--fill-hover);+}++.node-button strong {+ font-size: 11px;+}++.node-subtitle {+ font-size: 10px;+ color: var(--muted-foreground);+ overflow-wrap: anywhere;+}++.node-button [data-slot='badge'] {+ font-size: 9px;+ white-space: normal;+}++.node-package {+ top: 45px;+ left: 1.54%;+}++.node-release {+ top: 212px;+ left: 1.54%;+}++.node-base {+ top: 212px;+ left: 26.73%;+}++.node-pi {+ top: 97px;+ left: 51.92%;+}++.node-autoresearch {+ top: 212px;+ left: 51.92%;+}++.node-vm {+ top: 327px;+ left: 51.92%;+}++.node-custom {+ top: 272px;+ left: 77.11%;+}++.node-dev_stack {+ top: 392px;+ left: 77.11%;+}++.node-notebook {+ top: 437px;+ left: 1.54%;+}++.node-streamlit {+ top: 437px;+ left: 26.73%;+}++.parallel-caption {+ position: absolute;+ top: 411px;+ left: 1.54%;+ font-size: 9px;+ color: var(--muted-foreground);+}++.pipeline-legend {+ padding: 14px 16px;+ font-size: 10px;+ color: var(--muted-foreground);+ border-top: 1px solid var(--border);+}++.inspector {+ gap: 14px;+ padding: 20px;+ font-size: 12px;+}++.inspector-header {+ display: flex;+ gap: 8px;+ align-items: center;+ justify-content: space-between;+}++.inspector p {+ font-size: 11px;+ line-height: 1.7;+ color: var(--muted-foreground);+}++.inspector dl {+ display: grid;+ grid-template-columns: 95px minmax(0, 1fr);+ gap: 8px;+ margin: 0;+ font-size: 11px;+}++.inspector dt {+ color: var(--muted-foreground);+}++.inspector dd {+ margin: 0;+ overflow-wrap: anywhere;+}++.platform-details {+ display: grid;+ gap: 10px;+ padding-top: 12px;+ border-top: 1px solid var(--border);+}++.digest {+ overflow-wrap: anywhere;+}++.run-link {+ display: flex;+ gap: 8px;+ justify-content: space-between;+}++.empty-state,+.app-shell .alert {+ padding: 14px 18px;+}++.app-shell .alert {+ margin-bottom: 16px;+ background: var(--fill-hover);+ border: 1px solid var(--border);+}++.inventory table {+ width: 100%;+ table-layout: fixed;+}++.inventory td,+.inventory th {+ font-size: 11px;+ overflow-wrap: anywhere;+ white-space: normal;+}++.inventory [data-slot='badge'] {+ white-space: normal;+}++.source-row {+ display: flex;+ flex-wrap: wrap;+ gap: 16px;+ align-items: center;+ justify-content: space-between;+ padding: 16px 0;+ border-top: 1px solid var(--border);+}++.page-footer {+ display: flex;+ flex-wrap: wrap;+ gap: 16px;+ justify-content: space-between;+ margin: 24px 0;+ font-size: 10px;+ color: var(--muted-foreground);+}++@container (max-width: 1100px) {+ .workspace {+ grid-template-areas: 'pipeline' 'inspector' 'inventory';+ grid-template-columns: minmax(0, 1fr);+ }++ .summary-grid {+ grid-template-columns: repeat(2, minmax(0, 1fr));+ }+}++@container (max-width: 680px) {+ .pipeline-stage-labels,+ .connections,+ .parallel-caption {+ display: none;+ }++ .pipeline {+ display: grid;+ grid-template-columns: repeat(2, minmax(0, 1fr));+ gap: 14px;+ height: auto;+ padding: 16px;+ }++ .pipeline-node {+ position: static;+ width: auto;+ min-width: 0;+ }++ .node-package {+ grid-row: 1;+ grid-column: 1;+ }++ .node-release {+ grid-row: 1;+ grid-column: 2;+ }++ .node-base {+ grid-row: 2;+ grid-column: 1 / -1;+ }++ .node-pi {+ grid-row: 3;+ grid-column: 1;+ }++ .node-autoresearch {+ grid-row: 3;+ grid-column: 2;+ }++ .node-vm {+ grid-row: 4;+ grid-column: 1 / -1;+ }++ .node-custom {+ grid-row: 5;+ grid-column: 1;+ }++ .node-dev_stack {+ grid-row: 5;+ grid-column: 2;+ }++ .node-notebook {+ grid-row: 6;+ grid-column: 1;+ }++ .node-streamlit {+ grid-row: 6;+ grid-column: 2;+ }++ .inventory th,+ .inventory td {+ padding: 8px 4px;+ font-size: 10px;+ }++ .inventory code {+ font-size: 9px;+ }+}diff --git a/products/tasks/frontend/infrastructure/infrastructureAdmin.html b/products/tasks/frontend/infrastructure/infrastructureAdmin.htmlnew file mode 100644index 000000000000..b42a37a1d8e8--- /dev/null+++ b/products/tasks/frontend/infrastructure/infrastructureAdmin.html@@ -0,0 +1,15 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width,initial-scale=1" />+ <meta name="robots" content="noindex,nofollow" />+ <title>Agent infrastructure</title>+ <script nonce="{{ request.csp_nonce }}">+ window.JS_URL = '{{ js_url|escapejs }}'+ </script>+ </head>+ <body>+ <div id="root" data-region="{{ region|default:'local' }}"></div>+ </body>+</html>diff --git a/products/tasks/frontend/infrastructure/infrastructureLogic.ts b/products/tasks/frontend/infrastructure/infrastructureLogic.tsnew file mode 100644index 000000000000..b01f375ae021--- /dev/null+++ b/products/tasks/frontend/infrastructure/infrastructureLogic.ts@@ -0,0 +1,153 @@+import { MakeLogicType, actions, afterMount, kea, reducers } from 'kea'+import { disposables } from 'kea-disposables'+import { loaders } from 'kea-loaders'++import { Source, Sources, Workflow, sourceNames } from './infrastructureTypes'++async function readSource<T>(name: string, imageId?: string): Promise<Source<T>> {+ const url = new URL(window.location.href)+ url.search = new URLSearchParams({ source: name, ...(imageId ? { image_id: imageId } : {}) }).toString()+ const response = await fetch(url, { signal: AbortSignal.timeout(60_000), credentials: 'same-origin' })+ if (!response.ok || !response.headers.get('content-type')?.includes('application/json')) {+ throw new Error('Source unavailable. Refresh the page to check your admin session.')+ }+ return response.json()+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface infrastructureLogicValues {+ now: number+ paused: boolean+ selected: string+ showSources: boolean+ sources: Sources | null+ sourcesLoading: boolean+ workflow: {+ id: string+ source: Source<Workflow>+ } | null+ workflowLoading: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface infrastructureLogicActions {+ loadSources: () => any+ loadSourcesFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadSourcesSuccess: (+ sources: Sources,+ payload?: any+ ) => {+ sources: Sources+ payload?: any+ }+ loadWorkflow: ({ id }: { id: string }) => {+ id: string+ }+ loadWorkflowFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadWorkflowSuccess: (+ workflow: {+ id: string+ source: Source<Workflow>+ },+ payload?: {+ id: string+ }+ ) => {+ workflow: {+ id: string+ source: Source<Workflow>+ }+ payload?: {+ id: string+ }+ }+ setPaused: (paused: boolean) => {+ paused: boolean+ }+ setSelected: (selected: string) => { selected: string }+ setShowSources: (showSources: boolean) => { showSources: boolean }+ tick: () => {+ now: number+ }+}++export type infrastructureLogicType = MakeLogicType<infrastructureLogicValues, infrastructureLogicActions>++export const infrastructureLogic = kea<infrastructureLogicType>([+ actions({+ setPaused: (paused: boolean) => ({ paused }),+ setSelected: (selected: string) => ({ selected }),+ setShowSources: (showSources: boolean) => ({ showSources }),+ tick: () => ({ now: Date.now() }),+ }),+ reducers({+ paused: [false, { setPaused: (_, { paused }) => paused }],+ selected: ['custom', { setSelected: (_, { selected }) => selected }],+ showSources: [false, { setShowSources: (_, { showSources }) => showSources }],+ now: [Date.now(), { tick: (_, { now }) => now }],+ }),+ loaders(({ values }) => ({+ sources: [+ null as Sources | null,+ {+ loadSources: async () =>+ Object.fromEntries(+ await Promise.all(+ sourceNames.map(async (name) => {+ try {+ return [name, await readSource(name)]+ } catch {+ return [name, { ...values.sources?.[name], status: 'error' }]+ }+ })+ )+ ) as Sources,+ },+ ],+ workflow: [+ null as { id: string; source: Source<Workflow> } | null,+ {+ loadWorkflow: async ({ id }: { id: string }, breakpoint) => {+ let source: Source<Workflow>+ try {+ source = await readSource<Workflow>('workflow', id)+ } catch {+ source = { status: 'error', data: null, observed_at: null }+ }+ breakpoint()+ return { id, source }+ },+ },+ ],+ })),+ disposables(({ actions, values }) => ({+ clock: () => {+ const timer = setInterval(() => actions.tick(), 10_000)+ return () => clearInterval(timer)+ },+ poll: () => {+ const timer = setInterval(() => {+ if (!values.paused && !values.sourcesLoading) {+ actions.loadSources()+ if (values.workflow && !values.workflowLoading) {+ actions.loadWorkflow({ id: values.workflow.id })+ }+ }+ }, 60_000)+ return () => clearInterval(timer)+ },+ })),+ afterMount(({ actions }) => actions.loadSources()),+])diff --git a/products/tasks/frontend/infrastructure/infrastructureTypes.test.ts b/products/tasks/frontend/infrastructure/infrastructureTypes.test.tsnew file mode 100644index 000000000000..2aa3e233066d--- /dev/null+++ b/products/tasks/frontend/infrastructure/infrastructureTypes.test.ts@@ -0,0 +1,93 @@+import { CustomImage, Source, SourceData, Sources, customState, imageState, pinState } from './infrastructureTypes'++const image: CustomImage = {+ id: '00000000-0000-4000-8000-000000000001',+ team_id: 1,+ status: 'ready',+ version: 2,+ base_image_reference: 'old',+ base_image_refresh_reference: null,+ has_published_image: true,+ has_error: false,+ has_spec: true,+ updated_at: '2026-01-01T00:00:00Z',+ workflow_url: 'https://example.com/workflow',+}++describe('infrastructure rollout evidence', () => {+ it.each([+ [{}, 'waiting'],+ [{ has_error: true }, 'failed'],+ [{ base_image_reference: 'current' }, 'current'],+ [{ base_image_reference: null }, 'unknown'],+ [{ status: 'building', base_image_refresh_reference: 'current' }, 'building'],+ [{ has_spec: false }, 'unmanaged'],+ [{ has_published_image: false }, 'unmanaged'],+ ] as const)('classifies custom image %j as %s', (changes, expected) => {+ expect(customState({ ...image, ...changes }, 'current')).toEqual(expected)+ })++ it.each(['notebook', 'streamlit', 'pi', 'autoresearch', 'vm'] as const)(+ 'requires matching lineage on both platforms and fresh evidence for %s',+ (name) => {+ const observed_at = new Date().toISOString()+ const platforms = ['amd64', 'arm64'].map((arch) => ({+ arch,+ version: '1.0.0',+ revision: 'base-revision',+ base_revision: 'base-revision',+ inputs_digest: 'inputs',+ digest: `sha256:${arch}`,+ }))+ const sources: Sources = {+ release: { status: 'ok', observed_at, data: { pin: '1.0.0', runs: [] } },+ base: { status: 'ok', observed_at, data: { name: 'base', reference: 'base', platforms } },+ [name]: {+ status: 'ok',+ observed_at,+ data: { name, reference: name, platforms: structuredClone(platforms) },+ },+ }+ expect(imageState(sources, name)).toEqual('current')+ sources[name]!.data!.platforms[1].inputs_digest = 'old-inputs'+ expect(imageState(sources, name)).toEqual('waiting')+ sources[name]!.data!.platforms[1].inputs_digest = 'inputs'+ sources[name]!.data!.platforms[1].base_revision = 'old-base'+ expect(imageState(sources, name)).toEqual('waiting')+ sources[name]!.data!.platforms[1].base_revision = 'base-revision'+ sources.base!.status = 'error'+ expect(imageState(sources, name)).toEqual('unknown')+ }+ )++ it.each([+ ['1.0.0', '1.0.0', 'current'],+ ['1.1.0', '1.0.0', 'waiting'],+ ['', '1.0.0', 'unknown'],+ ['1.0.0', '', 'unknown'],+ ] as const)('compares package %s with pin %s', (version, pin, expected) => {+ const observed_at = new Date().toISOString()+ expect(+ pinState({+ package: { status: 'ok', observed_at, data: { version, revision: null } },+ release: { status: 'ok', observed_at, data: { pin, runs: [] } },+ })+ ).toEqual(expected)+ })++ it.each(['package', 'release'] as const)('requires fresh %s evidence for the pin', (name) => {+ const observed_at = new Date().toISOString()+ const sources: Sources = {+ package: { status: 'ok', observed_at, data: { version: '1.0.0', revision: null } },+ release: { status: 'ok', observed_at, data: { pin: '1.0.0', runs: [] } },+ }+ const source = sources[name] as Source<SourceData[typeof name]>+ source.observed_at = new Date(Date.now() - 300_000).toISOString()+ expect(pinState(sources)).toEqual('unknown')+ source.observed_at = observed_at+ source.status = 'error'+ expect(pinState(sources)).toEqual('unknown')+ delete sources[name]+ expect(pinState(sources)).toEqual('unknown')+ })+})diff --git a/products/tasks/frontend/infrastructure/infrastructureTypes.ts b/products/tasks/frontend/infrastructure/infrastructureTypes.tsnew file mode 100644index 000000000000..3bd6db860410--- /dev/null+++ b/products/tasks/frontend/infrastructure/infrastructureTypes.ts@@ -0,0 +1,138 @@+export const imageNames = ['base', 'notebook', 'streamlit', 'pi', 'autoresearch', 'vm'] as const+export type ImageName = (typeof imageNames)[number]+export type Evidence = 'current' | 'waiting' | 'building' | 'failed' | 'unknown' | 'unmanaged'+export type Source<T> = { status: 'ok' | 'error' | 'refreshing'; observed_at: string | null; data: T | null }+export type Platform = {+ arch: string+ version: string | null+ revision: string | null+ base_revision: string | null+ inputs_digest: string | null+ digest: string+}+export type RegistryImage = { name: string; reference: string; platforms: Platform[] }+export type CustomImage = {+ id: string+ team_id: number+ status: string+ version: number+ base_image_reference: string | null+ base_image_refresh_reference: string | null+ has_published_image: boolean+ has_error: boolean+ has_spec: boolean+ updated_at: string+ workflow_url: string+}+export type Workflow = {+ status: string+ run_id?: string+ started_at?: string | null+ closed_at?: string | null+ url: string+ activities: { name: string; state: string; attempt: number }[]+}+export type SourceData = {+ package: { version: string; revision: string | null }+ release: {+ pin: string+ runs: {+ id: number+ head_sha: string+ status: string+ conclusion: string | null+ html_url: string+ created_at: string+ build_jobs: { name: string; status: string; conclusion: string | null; promotion: string | null }[]+ }[]+ }+ custom: { images: CustomImage[]; truncated: boolean; limit: number }+ dev_stack: { name: string; base_image_reference: string | null; workflow_url: string }+} & Record<ImageName, RegistryImage>+export type Sources = { [K in keyof SourceData]?: Source<SourceData[K]> }+export const sourceNames: (keyof SourceData)[] = ['package', 'release', ...imageNames, 'custom', 'dev_stack']+export const labels: Record<Evidence, string> = {+ current: 'Current',+ waiting: 'Awaiting refresh',+ building: 'Building',+ failed: 'Failed',+ unknown: 'Unverified',+ unmanaged: 'Not eligible',+}+export const variants = {+ current: 'success',+ waiting: 'warning',+ building: 'info',+ failed: 'destructive',+ unknown: 'default',+ unmanaged: 'default',+} as const++export function fresh(source: Source<unknown> | undefined, now = Date.now()): boolean {+ return source?.status === 'ok' && !!source.observed_at && now - Date.parse(source.observed_at) < 150_000+}++export function pinState(sources: Sources): Evidence {+ if (+ !fresh(sources.package) ||+ !fresh(sources.release) ||+ !sources.package?.data?.version ||+ !sources.release?.data?.pin+ ) {+ return 'unknown'+ }+ return sources.package.data.version === sources.release.data.pin ? 'current' : 'waiting'+}++export function imageState(sources: Sources, name: ImageName): Evidence {+ const source = sources[name]+ if (!fresh(source) || !fresh(sources.release) || !source?.data || !sources.release?.data) {+ return 'unknown'+ }+ const platforms = source.data.platforms+ if (+ !['amd64', 'arm64'].every((arch) =>+ platforms.some((p) => p.arch === arch && p.version === sources.release?.data?.pin)+ )+ ) {+ return 'waiting'+ }+ if (name !== 'base') {+ if (!fresh(sources.base) || !sources.base?.data) {+ return 'unknown'+ }+ if (+ !platforms.every((p) => {+ const base = sources.base?.data?.platforms.find((b) => b.arch === p.arch)+ return (+ !!base?.revision &&+ !!base.inputs_digest &&+ p.base_revision === base.revision &&+ p.inputs_digest === base.inputs_digest+ )+ })+ ) {+ return 'waiting'+ }+ }+ return 'current'+}++export function customState(image: CustomImage, currentBase: string | undefined): Evidence {+ if (['building', 'scanning'].includes(image.status)) {+ return 'building'+ }+ if (['build_failed', 'scan_failed'].includes(image.status)) {+ return 'failed'+ }+ if (image.status !== 'ready' || !image.has_published_image || !image.has_spec) {+ return 'unmanaged'+ }+ if (!currentBase || !image.base_image_reference) {+ return 'unknown'+ }+ if (image.base_image_reference === currentBase) {+ return 'current'+ }+ return image.has_error ? 'failed' : 'waiting'+}diff --git a/products/tasks/frontend/infrastructure/mountInfrastructureAdmin.tsx b/products/tasks/frontend/infrastructure/mountInfrastructureAdmin.tsxnew file mode 100644index 000000000000..1d91457001fe--- /dev/null+++ b/products/tasks/frontend/infrastructure/mountInfrastructureAdmin.tsx@@ -0,0 +1,29 @@+import './infrastructureAdmin.css'++import { resetContext } from 'kea'+import { disposablesPlugin } from 'kea-disposables'+import { loadersPlugin } from 'kea-loaders'+import { createRoot } from 'react-dom/client'++import { ThemeProvider } from '@posthog/quill'++import { InfrastructureAdmin } from './InfrastructureAdmin'++resetContext({ plugins: [loadersPlugin(), disposablesPlugin] })++function mount(): void {+ const root = document.getElementById('root')+ if (root) {+ createRoot(root).render(+ <ThemeProvider defaultTheme="light">+ <InfrastructureAdmin region={root.dataset.region || 'local'} />+ </ThemeProvider>+ )+ }+}++if (document.readyState === 'loading') {+ document.addEventListener('DOMContentLoaded', mount, { once: true })+} else {+ mount()+}diff --git a/products/tasks/package.json b/products/tasks/package.jsonindex 03f052e2b68f..4faf9f851e99 100644--- a/products/tasks/package.json+++ b/products/tasks/package.json@@ -5,10 +5,12 @@},"dependencies": {"@posthog/products-mcp-store": "workspace:*",- "@posthog/quill": "workspace:*"+ "@posthog/quill": "workspace:*",+ "kea-disposables": "catalog:"},"devDependencies": {- "kea-test-utils": "catalog:"+ "kea-test-utils": "catalog:",+ "tailwindcss": "4.3.0"},"peerDependencies": {"@posthog/icons": "catalog:",