Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(tasks): mint preview connect credentials for a sandbox port (#89975)

Alessandro Pogliaghi4b957317966c
diff --git a/products/tasks/backend/constants.py b/products/tasks/backend/constants.py
index ea2fe7b72120..723da5198c74 100644
--- a/products/tasks/backend/constants.py
+++ b/products/tasks/backend/constants.py
@@ -68,6 +68,10 @@ def is_same_run_resume_idle_state(state: Mapping[str, Any] | None) -> bool:
)
+DEV_STACK_PREVIEW_STATE_KEY = "dev_stack_preview"
+DEV_STACK_PREVIEW_FEATURE_FLAG = "tasks-dev-stack-preview"
+DEV_STACK_PREVIEW_PORT = 8020
+
# Models a caller may only select while the paired flag is enabled for them. The Desktop
# pickers already hide these client-side (`products/desktop/packages/shared/src/flags.ts`),
# but a picker is a convenience rather than a gate: a stored per-task model preference, an
diff --git a/products/tasks/backend/logic/services/docker_sandbox.py b/products/tasks/backend/logic/services/docker_sandbox.py
index 436e05b51b5d..093313ab7039 100644
--- a/products/tasks/backend/logic/services/docker_sandbox.py
+++ b/products/tasks/backend/logic/services/docker_sandbox.py
@@ -18,7 +18,7 @@ from collections.abc import Iterable, Iterator
from contextlib import contextmanager
from contextvars import ContextVar
from pathlib import Path
-from typing import TYPE_CHECKING, Optional
+from typing import TYPE_CHECKING, Any, Optional
from django.conf import settings
@@ -753,7 +753,7 @@ class DockerSandbox(SandboxBase):
return _DockerExecutionStream(process, timeout_seconds, self.id)
- def write_file(self, path: str, payload: bytes) -> ExecutionResult:
+ def write_file(self, path: str, payload: bytes, timeout_seconds: int | None = None) -> ExecutionResult:
if not self.is_running():
raise SandboxExecutionError(
"Sandbox not in running state.",
@@ -761,6 +761,7 @@ class DockerSandbox(SandboxBase):
cause=RuntimeError(f"Sandbox {self.id} is not running"),
)
+ step_timeout = timeout_seconds or self.config.default_execution_timeout_seconds
chunk_size = 50000
encoded_payload = base64.b64encode(payload).decode("utf-8")
temp_path = f"{path}.tmp-{uuid.uuid4().hex}"
@@ -781,7 +782,7 @@ class DockerSandbox(SandboxBase):
" response_file.write(payload)\n"
"EOF_SANDBOX_WRITE"
)
- result = self.execute(command, timeout_seconds=self.config.default_execution_timeout_seconds)
+ result = self.execute(command, timeout_seconds=step_timeout)
if result.exit_code != 0:
logger.warning(
"sandbox_write_failed",
@@ -791,7 +792,7 @@ class DockerSandbox(SandboxBase):
if result.exit_code == 0:
move_command = f"mv {shlex.quote(temp_path)} {shlex.quote(path)}"
- result = self.execute(move_command, timeout_seconds=self.config.default_execution_timeout_seconds)
+ result = self.execute(move_command, timeout_seconds=step_timeout)
if result.exit_code != 0:
logger.warning(
"sandbox_write_failed",
@@ -852,6 +853,9 @@ class DockerSandbox(SandboxBase):
logger.info(f"Got connect credentials for sandbox {self.id}: {url}")
return AgentServerResult(url=url, token=None)
+ def create_preview_connect_credentials(self, port: int, user_metadata: dict[str, Any]) -> AgentServerResult:
+ raise NotImplementedError("Docker sandboxes do not support preview connect tokens")
+
def _build_agent_server_command(
self,
repo_path: str | None,
diff --git a/products/tasks/backend/logic/services/hogland_sandbox.py b/products/tasks/backend/logic/services/hogland_sandbox.py
index 0db664a71787..c0b1e8e1ce4a 100644
--- a/products/tasks/backend/logic/services/hogland_sandbox.py
+++ b/products/tasks/backend/logic/services/hogland_sandbox.py
@@ -25,6 +25,7 @@ import logging
from collections.abc import Iterable
from functools import lru_cache
from pathlib import Path
+from typing import Any
from django.conf import settings
@@ -359,7 +360,7 @@ class HoglandSandbox(AgentServerLaunchMixin):
events = self._box.exec_stream(["bash", "-c", command], timeout_seconds=timeout_seconds)
return _HogboxExecutionStream(events)
- def write_file(self, path: str, payload: bytes) -> ExecutionResult:
+ def write_file(self, path: str, payload: bytes, timeout_seconds: int | None = None) -> ExecutionResult:
if not self.is_running():
raise SandboxNotRunningError(
"Sandbox not in running state.",
@@ -393,6 +394,9 @@ class HoglandSandbox(AgentServerLaunchMixin):
logger.info(f"Got connect credentials for sandbox {self.id}: {self._sandbox_url}")
return AgentServerResult(url=self._sandbox_url, token=None)
+ def create_preview_connect_credentials(self, port: int, user_metadata: dict[str, Any]) -> AgentServerResult:
+ raise NotImplementedError("Hogland sandboxes do not support preview connect tokens")
+
def setup_repository(self, repository: str) -> ExecutionResult:
"""No-op: repository setup is handled by agent-server."""
return ExecutionResult(stdout="", stderr="", exit_code=0, error=None)
diff --git a/products/tasks/backend/logic/services/modal_sandbox.py b/products/tasks/backend/logic/services/modal_sandbox.py
index 6181e79a652b..8b8a0f3a1234 100644
--- a/products/tasks/backend/logic/services/modal_sandbox.py
+++ b/products/tasks/backend/logic/services/modal_sandbox.py
@@ -1126,7 +1126,7 @@ class ModalSandbox(AgentServerLaunchMixin):
return _ModalExecutionStream(process)
- def write_file(self, path: str, payload: bytes) -> ExecutionResult:
+ def write_file(self, path: str, payload: bytes, timeout_seconds: int | None = None) -> ExecutionResult:
if not self.is_running():
raise SandboxNotRunningError(
"Sandbox not in running state.",
@@ -1138,7 +1138,9 @@ class ModalSandbox(AgentServerLaunchMixin):
try:
self._sandbox.filesystem.write_bytes(payload, temp_path)
mv_command = f"mv {shlex.quote(temp_path)} {shlex.quote(path)}"
- result = self.execute(mv_command, timeout_seconds=self.config.default_execution_timeout_seconds)
+ result = self.execute(
+ mv_command, timeout_seconds=timeout_seconds or self.config.default_execution_timeout_seconds
+ )
if result.exit_code != 0:
logger.warning(
"sandbox_write_failed",
@@ -1191,6 +1193,15 @@ class ModalSandbox(AgentServerLaunchMixin):
logger.info(f"Got connect credentials for sandbox {self.id}: {credentials.url}")
return AgentServerResult(url=credentials.url, token=credentials.token)
+ def create_preview_connect_credentials(self, port: int, user_metadata: dict[str, Any]) -> AgentServerResult:
+ if not self.is_running():
+ raise RuntimeError("Sandbox not in running state.")
+
+ credentials = self._sandbox.create_connect_token(user_metadata=user_metadata, port=port)
+
+ logger.info(f"Minted preview connect credentials for sandbox {self.id} on port {port}")
+ return AgentServerResult(url=credentials.url, token=credentials.token)
+
def _termination_failure_reason(self) -> str:
poll = self._sandbox.poll()
return (
diff --git a/products/tasks/backend/logic/services/sandbox.py b/products/tasks/backend/logic/services/sandbox.py
index 6ead2abe5ddf..beb1a1d6c638 100644
--- a/products/tasks/backend/logic/services/sandbox.py
+++ b/products/tasks/backend/logic/services/sandbox.py
@@ -19,16 +19,18 @@ import threading
from abc import ABC, abstractmethod
from collections.abc import Callable, Iterable
from contextlib import AbstractContextManager, nullcontext
-from dataclasses import dataclass
+from dataclasses import dataclass, field
from enum import Enum
from types import TracebackType
-from typing import TYPE_CHECKING, Protocol, Self
+from typing import TYPE_CHECKING, Any, Protocol, Self
from django.conf import settings
import structlog
from pydantic import BaseModel, model_validator
+from posthog.dataclasses import frozen
+
from products.tasks.backend.constants import (
DEFAULT_SANDBOX_WORKING_DIR,
DEV_STACK_IMAGE_NAME,
@@ -47,12 +49,12 @@ if TYPE_CHECKING:
from products.tasks.backend.temporal.process_task.utils import McpServerConfig
-@dataclass
+@frozen
class AgentServerResult:
"""Result from starting an agent server in a sandbox."""
url: str
- token: str | None = None
+ token: str | None = field(default=None, repr=False)
class SandboxStatus(str, Enum):
@@ -325,7 +327,7 @@ class SandboxBase(ABC):
def execute_stream(self, command: str, timeout_seconds: int | None = None) -> ExecutionStream: ...
@abstractmethod
- def write_file(self, path: str, payload: bytes) -> ExecutionResult: ...
+ def write_file(self, path: str, payload: bytes, timeout_seconds: int | None = None) -> ExecutionResult: ...
def stop_agent_server(self) -> ExecutionResult:
"""Stop the agent server gracefully so it can flush terminal events."""
@@ -499,6 +501,9 @@ class SandboxBase(ABC):
"""
...
+ @abstractmethod
+ def create_preview_connect_credentials(self, port: int, user_metadata: dict[str, Any]) -> AgentServerResult: ...
+
@abstractmethod
def start_agent_server(
self,
diff --git a/products/tasks/backend/logic/services/sandbox_config.py b/products/tasks/backend/logic/services/sandbox_config.py
index 42c5a9e54c68..f20158259b08 100644
--- a/products/tasks/backend/logic/services/sandbox_config.py
+++ b/products/tasks/backend/logic/services/sandbox_config.py
@@ -18,3 +18,5 @@ VM_SANDBOX_CPU_CORES = 8.0
MAX_SANDBOX_CPU_CORES = 16
MAX_SANDBOX_MEMORY_GB = 64
MAX_SANDBOX_TTL_SECONDS = SANDBOX_TTL_SECONDS
+
+DEV_STACK_PREVIEW_MEMORY_GB = 32.0
diff --git a/products/tasks/backend/metrics.py b/products/tasks/backend/metrics.py
index f5f5ea029558..a016ae274f14 100644
--- a/products/tasks/backend/metrics.py
+++ b/products/tasks/backend/metrics.py
@@ -168,6 +168,22 @@ DEV_STACK_IMAGE_BAKE_TOTAL = Counter(
labelnames=["outcome", "region", "trigger"],
)
+DEV_STACK_PREVIEW_BOOT_BUCKETS = [30.0, 60.0, 120.0, 180.0, 240.0, 300.0, 420.0, 600.0, 720.0]
+
+DEV_STACK_PREVIEW_BOOT_SECONDS = Histogram(
+ "posthog_tasks_dev_stack_preview_boot_seconds",
+ "Wall time from launching the dev stack in a run's sandbox to its preview answering health checks",
+ buckets=DEV_STACK_PREVIEW_BOOT_BUCKETS,
+)
+
+DEV_STACK_PREVIEW_TOTAL = Counter(
+ "posthog_tasks_dev_stack_preview_total",
+ "Dev stack preview lifecycle outcomes. started counts launches and attached counts re-entries that joined "
+ "a launch in progress; ready, failed, timed_out and cancelled each close one of those; launch_failed "
+ "counts start attempts that raised before launching.",
+ labelnames=["outcome"],
+)
+
# Connection lifetimes range from a few seconds (cold reconnect) to the
# per-connection cap. The 120s bucket isolates connections cut at the
diff --git a/products/tasks/backend/sandbox/images/start-dev-stack-preview.sh b/products/tasks/backend/sandbox/images/start-dev-stack-preview.sh
new file mode 100644
index 000000000000..e159e437dd30
--- /dev/null
+++ b/products/tasks/backend/sandbox/images/start-dev-stack-preview.sh
@@ -0,0 +1,212 @@
+#!/usr/bin/env bash
+set -Eeuo pipefail
+
+STATE_DIR=/tmp/posthog-preview
+STATUS_FILE="$STATE_DIR/status.json"
+LOCK_FILE="$STATE_DIR/lock"
+CADDYFILE="$STATE_DIR/Caddyfile"
+PROXY_CONTAINER=posthog-preview-proxy
+WEB_HEALTH_URL=http://localhost:8010/_health
+VITE_HEALTH_URL=http://127.0.0.1:8234/@vite/client
+HEALTH_TIMEOUT_SECONDS="${HEALTH_TIMEOUT_SECONDS:-360}"
+PREVIEW_LOGIN_PASSWORD=12345678
+
+mkdir -p "$STATE_DIR"
+
+now() { date -u +%Y-%m-%dT%H:%M:%SZ; }
+
+write_status() {
+ state="$1"
+ error="$(printf '%s' "${2:-}" | tr -d '"\\' | tr '\n\r\t' ' ' | cut -c1-500)"
+ {
+ printf '{"state":"%s","started_at":"%s","updated_at":"%s"' "$state" "$STARTED_AT" "$(now)"
+ if [ -n "$error" ]; then
+ printf ',"error":"%s"' "$error"
+ fi
+ printf '}\n'
+ } >"$STATUS_FILE.tmp" && mv "$STATUS_FILE.tmp" "$STATUS_FILE"
+}
+
+fail() {
+ trap - ERR
+ echo "preview_failed: $1" >&2
+ write_status failed "$1"
+ exit 1
+}
+
+on_unexpected_exit() {
+ trap - ERR
+ echo "preview_failed: unexpected exit at line $1" >&2
+ write_status failed "unexpected exit at line $1"
+ exit 1
+}
+
+proxy_is_running() {
+ [ "$(docker inspect -f '{{.State.Running}}' "$PROXY_CONTAINER" 2>/dev/null || true)" = "true" ]
+}
+
+web_is_healthy() {
+ curl -sf --max-time 5 "$WEB_HEALTH_URL" >/dev/null 2>&1
+}
+
+vite_is_healthy() {
+ curl -sf --max-time 5 "$VITE_HEALTH_URL" >/dev/null 2>&1
+}
+
+stack_is_healthy() {
+ web_is_healthy && vite_is_healthy
+}
+
+proxy_is_healthy() {
+ curl -sf --max-time 5 "http://127.0.0.1:${PREVIEW_PORT}/_health" >/dev/null 2>&1
+}
+
+probe() {
+ PROBE_STEP="$1"
+ PROBE_CODE="$(curl -s --max-time 30 -o /dev/null -w '%{http_code}' "${@:2}")"
+ case "$PROBE_CODE" in 2*) return 0 ;; *) return 1 ;; esac
+}
+
+app_is_usable() {
+ jar="$(mktemp)"
+ base="http://127.0.0.1:${PREVIEW_PORT}"
+ probe login -H "Host: $MODAL_HOST" -c "$jar" "$base/login" || return 1
+ csrf="$(awk '/csrftoken/ {print $7}' "$jar" | tail -n1)"
+ probe api_login -H "Host: $MODAL_HOST" -b "$jar" -c "$jar" -H 'Content-Type: application/json' \
+ -H "X-CSRFToken: $csrf" -H "Origin: https://$MODAL_HOST" -H "Referer: https://$MODAL_HOST/" \
+ -d "{\"email\":\"$PREVIEW_LOGIN_EMAIL\",\"password\":\"$PREVIEW_LOGIN_PASSWORD\"}" "$base/api/login/" || return 1
+ probe projects -H "Host: $MODAL_HOST" -b "$jar" "$base/api/projects/@current/" || return 1
+ rm -f "$jar"
+}
+
+preview_is_ready() {
+ stack_is_healthy && proxy_is_running && proxy_is_healthy && app_is_usable
+}
+
+STARTED_AT="$(now)"
+trap 'on_unexpected_exit $LINENO' ERR
+
+exec 9>"$LOCK_FILE"
+if ! flock -n 9; then
+ echo "preview_already_launching"
+ exit 0
+fi
+
+[ -n "${MODAL_HOST:-}" ] || fail "MODAL_HOST is required"
+[ -n "${PREVIEW_PORT:-}" ] || fail "PREVIEW_PORT is required"
+[ -n "${REPO_PATH:-}" ] || fail "REPO_PATH is required"
+
+if preview_is_ready; then
+ write_status ready
+ echo "preview_already_ready"
+ exit 0
+fi
+
+write_status starting
+
+cd "$REPO_PATH" || fail "repository checkout $REPO_PATH is missing"
+
+cat >"$CADDYFILE" <<CADDY
+{
+ auto_https off
+ admin off
+}
+:${PREVIEW_PORT} {
+ @metrics path /_metrics /_metrics/*
+ handle @metrics {
+ respond 404
+ }
+ @vite_ws {
+ header Connection *Upgrade*
+ header Upgrade websocket
+ query token=*
+ }
+ @vite {
+ path /@*
+ path /src/*
+ path /node_modules/*
+ path /public/*
+ path /__vite_ping
+ }
+ handle @vite_ws {
+ reverse_proxy 127.0.0.1:8234
+ }
+ handle @vite {
+ reverse_proxy 127.0.0.1:8234 {
+ header_up X-Forwarded-Proto https
+ }
+ }
+ handle {
+ reverse_proxy 127.0.0.1:8010 {
+ header_up X-Forwarded-Proto https
+ }
+ }
+}
+CADDY
+
+echo "== bootstrap-dev-stack =="
+if [ -x /usr/local/bin/bootstrap-dev-stack ]; then
+ /usr/local/bin/bootstrap-dev-stack || fail "bootstrap-dev-stack failed"
+fi
+
+echo "== preview proxy =="
+if proxy_is_running; then
+ echo "preview proxy already running"
+else
+ docker rm -f "$PROXY_CONTAINER" >/dev/null 2>&1 || true
+ docker run -d --name "$PROXY_CONTAINER" --network host --restart unless-stopped \
+ -v "$CADDYFILE":/etc/caddy/Caddyfile:ro \
+ caddy:2 caddy run -c /etc/caddy/Caddyfile ||
+ fail "could not start the preview proxy"
+fi
+
+echo "== pnpm install =="
+pnpm install --frozen-lockfile --prefer-offline || fail "pnpm install failed"
+
+echo "== uv sync =="
+uv sync || fail "uv sync failed"
+
+activate_failed=
+set +u
+# shellcheck disable=SC1091
+source .venv/bin/activate || activate_failed=1
+set -u
+[ -z "$activate_failed" ] || fail "could not activate the python environment"
+
+export MODAL_HOST
+export CADDY_HOST=:8000
+export SITE_URL="https://$MODAL_HOST"
+export JS_URL="https://$MODAL_HOST:443"
+export VITE_ALLOWED_HOSTS="$MODAL_HOST"
+export IS_BEHIND_PROXY=1
+export TRUST_ALL_PROXIES=1
+export DEBUG=1
+export COMPOSE_PROJECT_NAME=posthog
+export HOGLI_SKIP_ZOMBIE_CHECK=1
+
+echo "== hogli start =="
+hogli start -y -d || fail "hogli start failed"
+
+echo "== hogli wait =="
+hogli wait --timeout "$HEALTH_TIMEOUT_SECONDS" || fail "a dev stack process crashed or did not become ready within ${HEALTH_TIMEOUT_SECONDS}s"
+
+echo "== waiting for the web server, vite and the preview proxy =="
+deadline=$((SECONDS + 60))
+until stack_is_healthy; do
+ [ "$SECONDS" -lt "$deadline" ] || break
+ sleep 3
+done
+web_is_healthy || fail "the web server did not answer /_health after hogli wait"
+vite_is_healthy || fail "vite did not serve /@vite/client after hogli wait"
+proxy_is_healthy || fail "the preview proxy did not answer on port ${PREVIEW_PORT}: $(docker logs --tail 5 "$PROXY_CONTAINER" 2>&1 || true)"
+
+echo "== login probe =="
+if ! app_is_usable; then
+ echo "== setup_dev =="
+ python manage.py setup_dev --no-data || fail "setup_dev failed; the preview has no seeded login"
+ app_is_usable || fail "login probe failed at $PROBE_STEP through the preview proxy (HTTP $PROBE_CODE)"
+fi
+
+write_status ready
+echo "preview_ready"
diff --git a/products/tasks/backend/tests/test_dev_stack_image.py b/products/tasks/backend/tests/test_dev_stack_image.py
index 52e600d7a182..301e1014ba4a 100644
--- a/products/tasks/backend/tests/test_dev_stack_image.py
+++ b/products/tasks/backend/tests/test_dev_stack_image.py
@@ -51,7 +51,7 @@ def _make_fake_sandbox_cls(exit_code: int, publish_failures: int = 0):
def create(cls, config):
return cls()
- def write_file(self, path: str, payload: bytes) -> ExecutionResult:
+ def write_file(self, path: str, payload: bytes, timeout_seconds: int | None = None) -> ExecutionResult:
self.written_files[path] = payload
return ExecutionResult(stdout="", stderr="", exit_code=0, error=None)