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(streamlit-apps): add DRF API, HogQL bridge, proxy routes (#54879)

Jovan Sakovic530399aeb424
diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.py
index 0101bf9725aa..f9af9ca8fb93 100644
--- a/posthog/models/activity_logging/activity_log.py
+++ b/posthog/models/activity_logging/activity_log.py
@@ -92,6 +92,7 @@ ActivityScope = Literal[
"InstanceSetting",
"SignalReport",
"SignalScoutConfig",
+ "StreamlitApp",
]
ChangeAction = Literal[
"changed", "created", "deleted", "merged", "split", "exported", "revoked", "logged_in", "logged_out", "copied"
diff --git a/posthog/urls.py b/posthog/urls.py
index d0a2bdbe7f2f..323fff62d54e 100644
--- a/posthog/urls.py
+++ b/posthog/urls.py
@@ -70,6 +70,7 @@ from products.slack_app.backend.views import (
slack_user_link_authorize,
slack_user_link_callback,
)
+from products.streamlit_apps.backend.presentation.bridge_views import StreamlitBridgeView
from products.surveys.backend.api.survey import public_survey_page
from products.tasks.backend.facade.agent_proxy import agent_proxy_callback
from products.user_interviews.backend.presentation.webhooks import (
@@ -411,6 +412,11 @@ urlpatterns = [
include("products.access_control.backend.presentation.urls"),
),
opt_slash_path("api/support/ensure-zendesk-organization", csrf_exempt(ensure_zendesk_organization)),
+ path(
+ "api/streamlit_bridge/query/",
+ csrf_exempt(StreamlitBridgeView.as_view()),
+ name="streamlit_bridge_query",
+ ),
path("api/", include(router.urls)),
# Override the tf_urls QRGeneratorView to use the cache-aware version (handles session race conditions)
path("account/two_factor/qrcode/", CacheAwareQRGeneratorView.as_view()),
diff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.ts
index 53a064f8dd35..3e9622e8394f 100644
--- a/products/platform_features/frontend/generated/api.schemas.ts
+++ b/products/platform_features/frontend/generated/api.schemas.ts
@@ -996,6 +996,7 @@ export type ActivityLogListParams = {
* * `InstanceSetting` - InstanceSetting
* * `SignalReport` - SignalReport
* * `SignalScoutConfig` - SignalScoutConfig
+ * * `StreamlitApp` - StreamlitApp
* @minLength 1
*/
scope?: ActivityLogListScope
@@ -1078,6 +1079,7 @@ export const ActivityLogListScope = {
InstanceSetting: 'InstanceSetting',
SignalReport: 'SignalReport',
SignalScoutConfig: 'SignalScoutConfig',
+ StreamlitApp: 'StreamlitApp',
} as const
/**
@@ -1147,6 +1149,7 @@ export const ActivityLogListScope = {
* * `InstanceSetting` - InstanceSetting
* * `SignalReport` - SignalReport
* * `SignalScoutConfig` - SignalScoutConfig
+ * * `StreamlitApp` - StreamlitApp
*/
export type ActivityLogListScopesItem = (typeof ActivityLogListScopesItem)[keyof typeof ActivityLogListScopesItem]
@@ -1217,6 +1220,7 @@ export const ActivityLogListScopesItem = {
InstanceSetting: 'InstanceSetting',
SignalReport: 'SignalReport',
SignalScoutConfig: 'SignalScoutConfig',
+ StreamlitApp: 'StreamlitApp',
} as const
export type AdvancedActivityLogsListParams = {
diff --git a/products/streamlit_apps/backend/facade/api.py b/products/streamlit_apps/backend/facade/api.py
index 6c860d01596b..4b6a7df145c9 100644
--- a/products/streamlit_apps/backend/facade/api.py
+++ b/products/streamlit_apps/backend/facade/api.py
@@ -1,48 +1,87 @@
from __future__ import annotations
-from typing import TYPE_CHECKING
+import io
+import uuid
+import hashlib
+from django.db import IntegrityError, transaction
from django.db.models import QuerySet
+from django.utils import timezone
-if TYPE_CHECKING:
- from posthog.models.user import User
+import structlog
-from products.streamlit_apps.backend.facade.contracts import (
- AppContract,
- AppSandboxContract,
- AppVersionContract,
- ConnectInfoContract,
-)
+from posthog.models.activity_logging.activity_log import Detail, changes_between, log_activity
+from posthog.models.user import User
+from posthog.storage import object_storage
+
+from products.streamlit_apps.backend.facade import contracts
from products.streamlit_apps.backend.logic.app_runtime import (
AppRuntimeConcurrencyError,
AppRuntimeError,
AppRuntimeService,
- _sync_sandbox_status,
+ sync_sandbox_status,
)
+from products.streamlit_apps.backend.logic.bridge import execute_bridge_query
from products.streamlit_apps.backend.logic.oauth import (
- create_sandbox_bridge_token,
create_streamlit_access_token,
find_reusable_streamlit_access_token,
+ get_streamlit_oauth_app,
+)
+from products.streamlit_apps.backend.logic.zip_validator import MAX_ZIP_SIZE, validate_zip
+from products.streamlit_apps.backend.models import (
+ MAX_CPU_CORES,
+ MAX_MEMORY_GB,
+ MIN_CPU_CORES,
+ MIN_MEMORY_GB,
+ StreamlitApp,
+ StreamlitAppSandbox,
+ StreamlitAppVersion,
)
-from products.streamlit_apps.backend.logic.zip_validator import validate_zip
-from products.streamlit_apps.backend.models import StreamlitApp, StreamlitAppSandbox, StreamlitAppVersion
from products.streamlit_apps.backend.tasks import (
auto_restart_crashed_streamlit_sandboxes,
cleanup_deleted_streamlit_app_zips,
cleanup_expired_streamlit_oauth_tokens,
prune_old_streamlit_app_versions,
+ run_streamlit_app_lifecycle,
stop_idle_streamlit_sandboxes,
)
+logger = structlog.get_logger(__name__)
+
+_LAST_ACTIVITY_DEBOUNCE_SECONDS = 30
+
__all__ = [
"AppRuntimeConcurrencyError",
"AppRuntimeError",
- "create_sandbox_bridge_token",
- "validate_zip",
+ "AppNotFoundError",
+ "ZipTooLargeError",
+ "InvalidZipError",
+ "ConcurrentUploadError",
+ "VersionNotFoundError",
+ "NoActiveVersionError",
+ "AppNotRunningError",
+ "ConnectUnavailableError",
+ "MAX_ZIP_SIZE",
+ "MIN_CPU_CORES",
+ "MAX_CPU_CORES",
+ "MIN_MEMORY_GB",
+ "MAX_MEMORY_GB",
+ "check_zip_size",
"list_apps",
"get_app",
- "get_app_status",
+ "create_app",
+ "update_app",
+ "delete_app",
+ "list_versions",
+ "upload_version",
+ "activate_version",
+ "get_status",
+ "start_app",
+ "stop_app",
+ "restart_app",
"get_connect_info",
+ "execute_bridge_query",
+ "get_streamlit_oauth_app",
"auto_restart_crashed_streamlit_sandboxes",
"cleanup_deleted_streamlit_app_zips",
"cleanup_expired_streamlit_oauth_tokens",
@@ -51,20 +90,97 @@ __all__ = [
]
-def _version_to_contract(version: StreamlitAppVersion) -> AppVersionContract:
- return AppVersionContract(
+class AppNotFoundError(Exception):
+ def __init__(self, short_id: str) -> None:
+ self.short_id = short_id
+ super().__init__(f"App {short_id!r} not found.")
+
+
+class ZipTooLargeError(Exception):
+ def __init__(self) -> None:
+ super().__init__(f"Zip file too large (max {MAX_ZIP_SIZE // (1024 * 1024)} MB).")
+
+
+class InvalidZipError(Exception):
+ def __init__(self, errors: list[str]) -> None:
+ self.errors = errors
+ super().__init__("Invalid zip file: " + "; ".join(errors))
+
+
+class ConcurrentUploadError(Exception):
+ def __init__(self) -> None:
+ super().__init__("Concurrent upload detected. Please try again.")
+
+
+class VersionNotFoundError(Exception):
+ def __init__(self) -> None:
+ super().__init__("Version not found.")
+
+
+class NoActiveVersionError(Exception):
+ def __init__(self) -> None:
+ super().__init__("No active version. Upload a zip file first.")
+
+
+class AppNotRunningError(Exception):
+ def __init__(self) -> None:
+ super().__init__("App is not running.")
+
+
+class ConnectUnavailableError(Exception):
+ def __init__(self) -> None:
+ super().__init__("Unable to connect to app.")
+
+
+# --- Converters (model -> DTO) ---
+
+
+def _hedgehog_config(user: User) -> dict | None:
+ if not user.hedgehog_config:
+ return None
+ if user.hedgehog_config.get("version") == 2:
+ actor_options = user.hedgehog_config.get("actor_options", {})
+ return {
+ "use_as_profile": user.hedgehog_config.get("use_as_profile"),
+ "color": actor_options.get("color"),
+ "accessories": actor_options.get("accessories"),
+ "skin": actor_options.get("skin"),
+ }
+ return {
+ "use_as_profile": user.hedgehog_config.get("use_as_profile"),
+ "color": user.hedgehog_config.get("color"),
+ "accessories": user.hedgehog_config.get("accessories"),
+ "skin": user.hedgehog_config.get("skin"),
+ }
+
+
+def _to_user_basic(user: User) -> contracts.StreamlitAppUserInfo:
+ return contracts.StreamlitAppUserInfo(
+ id=user.id,
+ uuid=user.uuid,
+ distinct_id=user.distinct_id,
+ first_name=user.first_name,
+ last_name=user.last_name,
+ email=user.email,
+ is_email_verified=user.is_email_verified,
+ hedgehog_config=_hedgehog_config(user),
+ role_at_organization=user.role_at_organization,
+ )
+
+
+def _version_to_contract(version: StreamlitAppVersion) -> contracts.AppVersionContract:
+ return contracts.AppVersionContract(
id=version.id,
version_number=version.version_number,
- zip_file=version.zip_file,
zip_hash=version.zip_hash,
snapshot_id=version.snapshot_id,
- created_by_id=version.created_by_id,
+ created_by=_to_user_basic(version.created_by) if version.created_by else None,
created_at=version.created_at,
)
-def _sandbox_to_contract(sandbox: StreamlitAppSandbox) -> AppSandboxContract:
- return AppSandboxContract(
+def _sandbox_to_contract(sandbox: StreamlitAppSandbox) -> contracts.AppSandboxContract:
+ return contracts.AppSandboxContract(
status=sandbox.status,
restart_count=sandbox.app.restart_count,
last_error=sandbox.last_error,
@@ -74,57 +190,368 @@ def _sandbox_to_contract(sandbox: StreamlitAppSandbox) -> AppSandboxContract:
)
-def _app_to_contract(app: StreamlitApp) -> AppContract:
+def _get_sandbox_or_none(app: StreamlitApp) -> StreamlitAppSandbox | None:
try:
- sandbox = _sandbox_to_contract(app.sandbox)
+ return app.sandbox
except StreamlitAppSandbox.DoesNotExist:
- sandbox = None
+ return None
+
- return AppContract(
+def _app_to_contract(app: StreamlitApp) -> contracts.AppContract:
+ sandbox = _get_sandbox_or_none(app)
+ return contracts.AppContract(
id=app.id,
short_id=app.short_id,
name=app.name,
description=app.description,
cpu_cores=app.cpu_cores,
memory_gb=app.memory_gb,
- is_active=not app.deleted,
+ status=sandbox.status if sandbox is not None else "stopped",
active_version=_version_to_contract(app.active_version) if app.active_version else None,
- sandbox=sandbox,
- created_by_id=app.created_by_id,
+ sandbox=_sandbox_to_contract(sandbox) if sandbox is not None else None,
+ created_by=_to_user_basic(app.created_by) if app.created_by else None,
created_at=app.created_at,
updated_at=app.updated_at,
)
-def list_apps(team_id: int) -> QuerySet[StreamlitApp]:
- return StreamlitApp.objects.for_team(team_id).filter(deleted=False)
+# --- Query helpers ---
-def get_app(team_id: int, short_id: str) -> StreamlitApp:
- return StreamlitApp.objects.for_team(team_id).get(short_id=short_id, deleted=False)
+def _app_queryset(team_id: int) -> QuerySet[StreamlitApp]:
+ return (
+ StreamlitApp.objects.for_team(team_id)
+ .filter(deleted=False)
+ .select_related("created_by", "active_version", "active_version__created_by", "sandbox", "sandbox__version")
+ )
-def get_app_status(app: StreamlitApp) -> AppSandboxContract | None:
+def _get_app(team_id: int, short_id: str) -> StreamlitApp:
try:
- sandbox = app.sandbox
- except StreamlitAppSandbox.DoesNotExist:
- return None
- sandbox = _sync_sandbox_status(sandbox)
+ return _app_queryset(team_id).get(short_id=short_id)
+ except StreamlitApp.DoesNotExist:
+ raise AppNotFoundError(short_id) from None
+
+
+def _get_sandbox_and_stop_if_live(app: StreamlitApp) -> None:
+ """Stop a running/starting sandbox so the next viewer request boots the
+ newly-activated version. Best-effort: failures are logged but don't fail
+ the version change."""
+ sandbox = _get_sandbox_or_none(app)
+ if sandbox is None:
+ return
+ if sandbox.status not in (StreamlitAppSandbox.Status.RUNNING, StreamlitAppSandbox.Status.STARTING):
+ return
+ try:
+ AppRuntimeService().stop_app(app)
+ except Exception:
+ logger.warning("streamlit_app_stop_on_version_change_failed", app_id=str(app.id), exc_info=True)
+
+
+def _validate_resource_bounds(cpu_cores: float | None, memory_gb: float | None) -> None:
+ if cpu_cores is not None and (cpu_cores < MIN_CPU_CORES or cpu_cores > MAX_CPU_CORES):
+ raise ValueError(f"CPU cores must be between {MIN_CPU_CORES} and {MAX_CPU_CORES}.")
+ if memory_gb is not None and (memory_gb < MIN_MEMORY_GB or memory_gb > MAX_MEMORY_GB):
+ raise ValueError(f"Memory must be between {MIN_MEMORY_GB} and {MAX_MEMORY_GB} GB.")
+
+
+def check_zip_size(declared_size: int | None) -> None:
+ """Reject an oversized upload by its declared size. Exposed so callers can check
+ before reading the body into memory (`upload_version` also checks it after read)."""
+ if declared_size is not None and declared_size > MAX_ZIP_SIZE:
+ raise ZipTooLargeError()
+
+
+# --- App API ---
+
+
+def list_apps(team_id: int) -> list[contracts.AppContract]:
+ apps = _app_queryset(team_id).order_by("-updated_at")
+ return [_app_to_contract(app) for app in apps]
+
+
+def get_app(team_id: int, short_id: str) -> contracts.AppContract:
+ return _app_to_contract(_get_app(team_id, short_id))
+
+
+def create_app(
+ team_id: int, user: User, data: contracts.CreateAppInput, was_impersonated: bool
+) -> contracts.AppContract:
+ _validate_resource_bounds(data.cpu_cores, data.memory_gb)
+
+ app = StreamlitApp.objects.for_team(team_id).create(
+ team_id=team_id,
+ created_by=user,
+ name=data.name,
+ description=data.description,
+ cpu_cores=data.cpu_cores,
+ memory_gb=data.memory_gb,
+ )
+
+ log_activity(
+ organization_id=user.current_organization_id,
+ team_id=team_id,
+ user=user,
+ was_impersonated=was_impersonated,
+ item_id=str(app.id),
+ scope="StreamlitApp",
+ activity="created",
+ detail=Detail(name=app.name),
+ )
+
+ return _app_to_contract(app)
+
+
+def update_app(
+ team_id: int, short_id: str, user: User, data: contracts.UpdateAppInput, was_impersonated: bool
+) -> contracts.AppContract:
+ app = _get_app(team_id, short_id)
+ before_update = StreamlitApp.objects.for_team(team_id).get(pk=app.pk)
+
+ _validate_resource_bounds(data.cpu_cores, data.memory_gb)
+
+ if data.name is not None:
+ app.name = data.name
+ if data.description is not None:
+ app.description = data.description
+ if data.cpu_cores is not None:
+ app.cpu_cores = data.cpu_cores
+ if data.memory_gb is not None:
+ app.memory_gb = data.memory_gb
+ app.save()
+
+ changes = changes_between("StreamlitApp", previous=before_update, current=app)
+ if changes:
+ log_activity(
+ organization_id=user.current_organization_id,
+ team_id=team_id,
+ user=user,
+ was_impersonated=was_impersonated,
+ item_id=str(app.id),
+ scope="StreamlitApp",
+ activity="updated",
+ detail=Detail(changes=changes, name=app.name),
+ )
+
+ return _app_to_contract(app)
+
+
+def delete_app(team_id: int, short_id: str, user: User, was_impersonated: bool) -> None:
+ app = _get_app(team_id, short_id)
+
+ try:
+ AppRuntimeService().stop_app(app)
+ except Exception:
+ logger.warning("streamlit_app_stop_on_delete_failed", app_id=str(app.id))
+
+ app.deleted = True
+ app.deleted_at = timezone.now()
+ app.save(update_fields=["deleted", "deleted_at", "updated_at"])
+
+ log_activity(
+ organization_id=user.current_organization_id,
+ team_id=team_id,
+ user=user,
+ was_impersonated=was_impersonated,
+ item_id=str(app.id),
+ scope="StreamlitApp",
+ activity="deleted",
+ detail=Detail(name=app.name),
+ )
+
+
+# --- Version API ---
+
+
+def list_versions(team_id: int, short_id: str) -> list[contracts.AppVersionContract]:
+ app = _get_app(team_id, short_id)
+ versions = app.versions.select_related("created_by").order_by("-version_number")[:50]
+ return [_version_to_contract(v) for v in versions]
+
+
+def upload_version(
+ team_id: int,
+ short_id: str,
+ user: User,
+ file_content: bytes,
+ declared_size: int | None,
+ was_impersonated: bool,
+) -> contracts.AppVersionContract:
+ app = _get_app(team_id, short_id)
+
+ check_zip_size(declared_size)
+
+ validation = validate_zip(io.BytesIO(file_content))
+ if not validation.valid:
+ raise InvalidZipError(validation.errors)
+
+ zip_hash = hashlib.sha256(file_content).hexdigest()
+
+ version_id = uuid.uuid4()
+ zip_path = f"streamlit_apps/{app.team_id}/{app.id}/{version_id}.zip"
+ object_storage.write(zip_path, file_content)
+
+ def _cleanup_orphan() -> None:
+ try:
+ object_storage.delete(zip_path)
+ except Exception:
+ logger.warning("streamlit_upload_orphan_cleanup_failed", zip_path=zip_path, exc_info=True)
+
+ try:
+ with transaction.atomic():
+ latest_version = app.versions.select_for_update().order_by("-version_number").first()
+ next_version_number = (latest_version.version_number + 1) if latest_version else 1
+
+ version = StreamlitAppVersion.objects.create(
+ id=version_id,
+ app=app,
+ version_number=next_version_number,
+ zip_file=zip_path,
+ zip_hash=zip_hash,
+ created_by=user,
+ )
+
+ app.active_version = version
+ app.save(update_fields=["active_version", "updated_at"])
+ except IntegrityError:
+ _cleanup_orphan()
+ raise ConcurrentUploadError() from None
+ except Exception:
+ _cleanup_orphan()
+ raise
+
+ _get_sandbox_and_stop_if_live(app)
+
+ log_activity(
+ organization_id=user.current_organization_id,
+ team_id=team_id,
+ user=user,
+ was_impersonated=was_impersonated,
+ item_id=str(app.id),
+ scope="StreamlitApp",
+ activity="uploaded_version",
+ detail=Detail(name=f"{app.name} v{next_version_number}"),
+ )
+
+ return _version_to_contract(version)
+
+
+def activate_version(
+ team_id: int, short_id: str, user: User, version_number: int, was_impersonated: bool
+) -> contracts.AppVersionContract:
+ app = _get_app(team_id, short_id)
+ try:
+ version = app.versions.get(version_number=version_number)
+ except StreamlitAppVersion.DoesNotExist:
+ raise VersionNotFoundError() from None
+
+ app.active_version = version
+ app.save(update_fields=["active_version", "updated_at"])
+
+ _get_sandbox_and_stop_if_live(app)
+
+ log_activity(
+ organization_id=user.current_organization_id,
+ team_id=team_id,
+ user=user,
+ was_impersonated=was_impersonated,
+ item_id=str(app.id),
+ scope="StreamlitApp",
+ activity="activated_version",
+ detail=Detail(name=f"{app.name} v{version_number}"),
+ )
+
+ return _version_to_contract(version)
+
+
+# --- Sandbox lifecycle API ---
+
+
+def get_status(team_id: int, short_id: str) -> contracts.AppSandboxContract:
+ app = _get_app(team_id, short_id)
+ sandbox = _get_sandbox_or_none(app)
+ if sandbox is None:
+ return contracts.AppSandboxContract(
+ status="stopped",
+ restart_count=app.restart_count,
+ last_error="",
+ started_at=None,
+ last_activity_at=None,
+ version_number=None,
+ )
+ sandbox = sync_sandbox_status(sandbox)
return _sandbox_to_contract(sandbox)
-def get_connect_info(app: StreamlitApp, user: User, team_id: int) -> ConnectInfoContract:
- token_obj = find_reusable_streamlit_access_token(user, team_id)
- if token_obj is None:
- token_obj = create_streamlit_access_token(user, team_id)
+def start_app(team_id: int, short_id: str) -> tuple[contracts.AppContract, bool]:
+ """Returns (app, already_running). Dispatches the async lifecycle task unless
+ the sandbox is already running or starting."""
+ app = _get_app(team_id, short_id)
+ if not app.active_version:
+ raise NoActiveVersionError()
- runtime = AppRuntimeService()
- connect = runtime.get_connect_url(app, user_id=user.id, team_id=team_id)
- if connect is None:
- raise AppRuntimeError("App is not running.")
-
- return ConnectInfoContract(
- url=connect["url"],
- token=token_obj.token,
- expires_at=token_obj.expires,
+ sandbox = _get_sandbox_or_none(app)
+ already_running = sandbox is not None and sandbox.status in (
+ StreamlitAppSandbox.Status.RUNNING,
+ StreamlitAppSandbox.Status.STARTING,
+ )
+ if not already_running:
+ run_streamlit_app_lifecycle.delay(str(app.id), "start", team_id=app.team_id)
+
+ return _app_to_contract(app), already_running
+
+
+def stop_app(team_id: int, short_id: str) -> contracts.AppContract:
+ app = _get_app(team_id, short_id)
+ AppRuntimeService().stop_app(app)
+ return _app_to_contract(app)
+
+
+def restart_app(team_id: int, short_id: str) -> tuple[contracts.AppContract, bool]:
+ """Returns (app, transitioning). Dispatches the async lifecycle task unless
+ the sandbox is already starting or stopping."""
+ app = _get_app(team_id, short_id)
+ sandbox = _get_sandbox_or_none(app)
+ transitioning = sandbox is not None and sandbox.status in (
+ StreamlitAppSandbox.Status.STARTING,
+ StreamlitAppSandbox.Status.STOPPING,
)
+ if not transitioning:
+ run_streamlit_app_lifecycle.delay(str(app.id), "restart", team_id=app.team_id)
+
+ return _app_to_contract(app), transitioning
+
+
+def get_connect_info(team_id: int, short_id: str, user: User) -> contracts.StreamlitConnectInfo:
+ app = _get_app(team_id, short_id)
+ sandbox = _get_sandbox_or_none(app)
+ if sandbox is None or sandbox.status != StreamlitAppSandbox.Status.RUNNING:
+ raise AppNotRunningError()
+
+ runtime = AppRuntimeService()
+ connect_data = runtime.get_connect_url(app, user_id=user.id, team_id=team_id)
+ if not connect_data:
+ raise ConnectUnavailableError()
+
+ now = timezone.now()
+ if (
+ sandbox.last_activity_at is None
+ or (now - sandbox.last_activity_at).total_seconds() > _LAST_ACTIVITY_DEBOUNCE_SECONDS
+ ):
+ sandbox.last_activity_at = now
+ sandbox.save(update_fields=["last_activity_at"])
+
+ access_token = find_reusable_streamlit_access_token(user=user, team_id=team_id)
+ if access_token is None:
+ access_token = create_streamlit_access_token(user=user, team_id=team_id)
+
+ sandbox_url = connect_data["url"].rstrip("/")
+ # Docker sandboxes have no Modal connect token; only Modal tunnels need it.
+ modal_token = connect_data["token"]
+ iframe_url = f"{sandbox_url}/?_posthog_token={access_token.token}"
+ if modal_token:
+ iframe_url += f"&_modal_connect_token={modal_token}&_posthog_modal_token={modal_token}"
+
+ expires_in = max(0, int((access_token.expires - timezone.now()).total_seconds()))
+
+ return contracts.StreamlitConnectInfo(iframe_url=iframe_url, expires_in=expires_in)
diff --git a/products/streamlit_apps/backend/facade/contracts.py b/products/streamlit_apps/backend/facade/contracts.py
index 6fa84cb4d575..d179e6e6d726 100644
--- a/products/streamlit_apps/backend/facade/contracts.py
+++ b/products/streamlit_apps/backend/facade/contracts.py
@@ -1,18 +1,45 @@
+"""
+Contract types for streamlit_apps.
+
+Stable, framework-free frozen dataclasses that define what this product
+exposes to the rest of the codebase. No Django imports.
+
+These use ``pydantic.dataclasses.dataclass`` rather than the stdlib variant — same
+syntax, same ``is_dataclass()`` compatibility (so ``DataclassSerializer`` keeps
+working), but with runtime validation on construction. See
+``products/visual_review/backend/facade/contracts.py`` for the pattern this mirrors.
+"""
+
from __future__ import annotations
-from dataclasses import dataclass
from datetime import datetime
from uuid import UUID
+from pydantic.dataclasses import dataclass
+
+
+@dataclass(frozen=True)
+class StreamlitAppUserInfo:
+ """Lightweight user info for display purposes. Mirrors core UserBasicSerializer."""
+
+ id: int
+ uuid: UUID
+ distinct_id: str | None
+ first_name: str
+ last_name: str
+ email: str
+ is_email_verified: bool | None
+ hedgehog_config: dict | None
+ role_at_organization: str | None
+
@dataclass(frozen=True)
class AppVersionContract:
id: UUID
version_number: int
- zip_file: str
zip_hash: str
snapshot_id: str | None
- created_by_id: int | None
+ created_by: StreamlitAppUserInfo | None
created_at: datetime
@@ -34,10 +61,10 @@ class AppContract:
description: str
cpu_cores: float
memory_gb: float
- is_active: bool
+ status: str
active_version: AppVersionContract | None
sandbox: AppSandboxContract | None
- created_by_id: int | None
+ created_by: StreamlitAppUserInfo | None
created_at: datetime
updated_at: datetime
@@ -49,6 +76,14 @@ class ConnectInfoContract:
expires_at: datetime
+@dataclass(frozen=True)
+class StreamlitConnectInfo:
+ """Iframe connection info returned by the connect_info action."""
+
+ iframe_url: str
+ expires_in: int
+
+
@dataclass(frozen=True)
class CreateAppInput:
name: str
diff --git a/products/streamlit_apps/backend/logic/app_runtime.py b/products/streamlit_apps/backend/logic/app_runtime.py
index a6d8f95053ab..702b52ed721b 100644
--- a/products/streamlit_apps/backend/logic/app_runtime.py
+++ b/products/streamlit_apps/backend/logic/app_runtime.py
@@ -293,7 +293,7 @@ def _clear_sync_failures(sandbox_record: StreamlitAppSandbox) -> None:
cache.delete(_sync_failure_key(sandbox_record))
-def _sync_sandbox_status(sandbox_record: StreamlitAppSandbox) -> StreamlitAppSandbox:
+def sync_sandbox_status(sandbox_record: StreamlitAppSandbox) -> StreamlitAppSandbox:
"""Sync DB sandbox status with the Modal sandbox state.
Handles only RUNNING→STOPPED (died) and STARTING→ERROR (timed out).
@@ -495,7 +495,7 @@ class AppRuntimeService:
"restart_count": app.restart_count,
}
- sandbox_record = _sync_sandbox_status(sandbox_record)
+ sandbox_record = sync_sandbox_status(sandbox_record)
return {
"status": sandbox_record.status,
@@ -514,7 +514,7 @@ class AppRuntimeService:
if not sandbox_record or not sandbox_record.sandbox_id:
return None
- sandbox_record = _sync_sandbox_status(sandbox_record)
+ sandbox_record = sync_sandbox_status(sandbox_record)
if sandbox_record.status != StreamlitAppSandbox.Status.RUNNING:
return None
diff --git a/products/streamlit_apps/backend/logic/bridge.py b/products/streamlit_apps/backend/logic/bridge.py
index 4a730be2c867..7f249cc9ee35 100644
--- a/products/streamlit_apps/backend/logic/bridge.py
+++ b/products/streamlit_apps/backend/logic/bridge.py
@@ -35,15 +35,12 @@ def execute_bridge_query(query: str, team_id: int, client_query_id: str | None =
),
)
- if hasattr(response, "model_dump"):
- payload = response.model_dump(exclude_none=True)
- else:
- payload = response.dict(exclude_none=True)
-
- # TODO: Why are we reinventing the wheel here?
- # Allow-list the response shape so user code never sees internal fields.
+ # Deliberate allow-list off the typed response: HogQLQueryResponse also carries
+ # internal fields (hogql, the ClickHouse query, explain, timings) that sandbox
+ # user code must never see. Read the three presentation fields by name rather
+ # than dumping the whole model and re-picking string keys.
return {
- "columns": payload.get("columns") or [],
- "results": payload.get("results") or [],
- "types": payload.get("types") or [],
+ "columns": response.columns or [],
+ "results": response.results or [],
+ "types": response.types or [],
}
diff --git a/products/streamlit_apps/backend/logic/oauth.py b/products/streamlit_apps/backend/logic/oauth.py
index 5d29f39a76f5..e18ab691ba79 100644
--- a/products/streamlit_apps/backend/logic/oauth.py
+++ b/products/streamlit_apps/backend/logic/oauth.py
@@ -18,8 +18,10 @@ STREAMLIT_OAUTH_CLIENT_ID = "posthog-streamlit-apps-first-party"
ACCESS_TOKEN_EXPIRY_SECONDS = 60 * 60 # 1 hour
BRIDGE_TOKEN_EXPIRY_SECONDS = 60 * 20 # sandbox TTL + buffer
-# streamlit:iframe and streamlit:bridge suffixes let the proxy and the bridge
-# refuse tokens of the opposite type even if they leak between contexts.
+# streamlit:iframe and streamlit:bridge are deliberately internal first-party
+# discriminators, not registered API scopes: they never reach APIScopePermission
+# or a user-facing scope picker. They exist so the proxy and the bridge can refuse
+# tokens of the opposite type even if one leaks between contexts.
IFRAME_TOKEN_SCOPE = "streamlit:iframe"
BRIDGE_TOKEN_SCOPE = "query:read streamlit:bridge"
@@ -92,7 +94,12 @@ def find_reusable_streamlit_access_token(
def create_sandbox_bridge_token(user: User | None, team_id: int) -> str:
- """Mint a long-TTL OAuth token for the sandbox→PostHog HogQL bridge hop."""
+ """Mint a long-TTL OAuth token for the sandbox→PostHog HogQL bridge hop.
+
+ OAuth rather than a project secret API key is deliberate: the token carries a
+ `user`, which the bridge's org-membership re-check relies on to revoke access
+ when the minting user leaves the org. A PSAK is user-less and couldn't gate that.
+ """
oauth_app = get_streamlit_oauth_app()
token_value = generate_random_oauth_access_token(None)
diff --git a/products/streamlit_apps/backend/presentation/__init__.py b/products/streamlit_apps/backend/presentation/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/streamlit_apps/backend/presentation/bridge_views.py b/products/streamlit_apps/backend/presentation/bridge_views.py
new file mode 100644
index 000000000000..2c3f7db53509
--- /dev/null
+++ b/products/streamlit_apps/backend/presentation/bridge_views.py
@@ -0,0 +1,159 @@
+from __future__ import annotations
+
+import json
+import hashlib
+import logging
+
+from django.utils import timezone
+
+from rest_framework.permissions import AllowAny
+from rest_framework.request import Request
+from rest_framework.response import Response
+from rest_framework.views import APIView
+
+from posthog.models.organization import OrganizationMembership
+from posthog.models.team import Team
+from posthog.rate_limit import PersonalApiKeyRateThrottle
+
+from products.streamlit_apps.backend.facade.api import execute_bridge_query, get_streamlit_oauth_app
+from products.streamlit_apps.backend.presentation.serializers import streamlit_apps_flag_enabled
+
+logger = logging.getLogger(__name__)
+
+BRIDGE_REQUEST_MAX_BYTES = 16 * 1024
+
+
+class StreamlitBridgeThrottle(PersonalApiKeyRateThrottle):
+ scope = "streamlit_bridge"
+ rate = "120/hour"
+
+ def allow_request(self, request: Request, view: APIView) -> bool:
+ return self._allow_request_internal(request, view, personal_api_key_only=False)
+
+ def get_cache_key(self, request: Request, view: APIView) -> str:
+ auth_header = request.META.get("HTTP_AUTHORIZATION", "")
+ if auth_header.startswith("Bearer "):
+ token = auth_header[len("Bearer ") :]
+ ident = hashlib.sha256(token.encode()).hexdigest()[:32]
+ else:
+ ident = self.get_ident(request)
+ return self.cache_format % {"scope": self.scope, "ident": ident}
+
+
+class StreamlitBridgeIPThrottle(PersonalApiKeyRateThrottle):
+ """IP-keyed companion to StreamlitBridgeThrottle.
+
+ The per-token throttle is bucketed by the (unvalidated) bearer value, so an
+ unauthenticated caller could rotate a fresh random token per request and dodge
+ it while still forcing OAuth token lookups. This throttle caps total attempts
+ per source IP regardless of token, closing that bypass. Kept higher than the
+ per-token rate because legitimate sandboxes may share an egress IP.
+ """
+
+ scope = "streamlit_bridge_ip"
+ rate = "600/hour"
+
+ def allow_request(self, request: Request, view: APIView) -> bool:
+ return self._allow_request_internal(request, view, personal_api_key_only=False)
+
+ def get_cache_key(self, request: Request, view: APIView) -> str:
+ return self.cache_format % {"scope": self.scope, "ident": self.get_ident(request)}
+
+
+def _authenticate_bearer(auth_header: str) -> tuple[int | None, str | None, str | None]:
+ """Validate a bridge bearer token; returns (team_id, user_distinct_id, error).
+
+ Kept as an in-view helper rather than a DRF BaseAuthentication class on purpose:
+ this is a single first-party endpoint with bespoke checks (single-team scope,
+ iframe-vs-bridge discriminator, org-membership re-check), so a shared auth class
+ would be premature. If another product (e.g. Notebooks) grows the same
+ sandbox→bridge shape, extract a shared authenticator then.
+ """
+ from posthog.models.oauth import find_oauth_access_token
+
+ token = auth_header[len("Bearer ") :]
+
+ access_token = find_oauth_access_token(token)
+ if access_token is None:
+ return None, None, "Invalid token."
+ if access_token.expires and access_token.expires < timezone.now():
+ return None, None, "Token expired."
+ if not access_token.scoped_teams:
+ return None, None, "Token has no team scope."
+ scopes = (access_token.scope or "").split()
+ if "query:read" not in scopes:
+ return None, None, "Insufficient scope."
+ if "streamlit:bridge" not in scopes:
+ return None, None, "Token is not a bridge token."
+ if access_token.application_id != get_streamlit_oauth_app().id:
+ return None, None, "Invalid token application."
+ if len(access_token.scoped_teams) != 1:
+ return None, None, "Token must be scoped to exactly one team."
+
+ team_id = access_token.scoped_teams[0]
+
+ # The token outlives membership changes, so re-validate the minting user
+ # against the scoped team rather than trusting the embedded scope. A
+ # deactivated user, or one removed from the org, must lose bridge access.
+ user = access_token.user
+ if user is None or not user.is_active:
+ return None, None, "Token user is inactive."
+
+ team = Team.objects.filter(id=team_id).only("organization_id").first()
+ if team is None:
+ return None, None, "Token team not found."
+ if not OrganizationMembership.objects.filter(user=user, organization_id=team.organization_id).exists():
+ return None, None, "Token user is not a member of the team's organization."
+
+ return team_id, user.distinct_id, None
+
+
+def _streamlit_apps_enabled_for_team(team_id: int, user_distinct_id: str | None) -> bool:
+ team = Team.objects.filter(id=team_id).only("organization_id").first()
+ if team is None:
+ return False
+ org_id = str(team.organization_id)
+ return streamlit_apps_flag_enabled(user_distinct_id or org_id, org_id)
+
+
+class StreamlitBridgeView(APIView):
+ authentication_classes: list = []
+ permission_classes = [AllowAny]
+ throttle_classes = [StreamlitBridgeThrottle, StreamlitBridgeIPThrottle]
+ http_method_names = ["post"]
+
+ def post(self, request: Request) -> Response:
+ auth_header = request.META.get("HTTP_AUTHORIZATION", "")
+ if not auth_header.startswith("Bearer "):
+ return Response({"error": "Missing or invalid Authorization header."}, status=401)
+
+ team_id, user_distinct_id, error = _authenticate_bearer(auth_header)
+ if team_id is None:
+ return Response({"error": error}, status=401)
+
+ # Same gate as the viewset: a bridge token outlives a flag rollback,
+ # so the flag must be re-checked here, not just at token mint time.
+ if not _streamlit_apps_enabled_for_team(team_id, user_distinct_id):
+ return Response({"error": "Streamlit apps is not available."}, status=403)
+
+ if len(request.body) > BRIDGE_REQUEST_MAX_BYTES:
+ return Response({"error": "Request body too large."}, status=413)
+
+ try:
+ body = json.loads(request.body)
+ except json.JSONDecodeError:
+ return Response({"error": "Invalid JSON body."}, status=400)
+
+ query = body.get("query")
+ if not isinstance(query, str) or not query.strip():
+ return Response({"error": "Missing or empty 'query' field."}, status=400)
+
+ try:
+ result = execute_bridge_query(query=query, team_id=team_id)
+ return Response(result)
+ except Exception:
+ logger.exception(
+ "streamlit_bridge_query_failed",
+ extra={"team_id": team_id},
+ )
+ return Response({"error": "Query execution failed."}, status=400)
diff --git a/products/streamlit_apps/backend/presentation/serializers.py b/products/streamlit_apps/backend/presentation/serializers.py
new file mode 100644
index 000000000000..f737583313ca
--- /dev/null
+++ b/products/streamlit_apps/backend/presentation/serializers.py
@@ -0,0 +1,153 @@
+from typing import TYPE_CHECKING, cast
+
+import posthoganalytics
+from rest_framework import serializers
+from rest_framework.permissions import BasePermission
+from rest_framework.request import Request
+from rest_framework.views import APIView
+from rest_framework_dataclasses.serializers import DataclassSerializer
+
+from products.streamlit_apps.backend.facade.contracts import (
+ AppContract,
+ AppSandboxContract,
+ AppVersionContract,
+ CreateAppInput,
+ StreamlitAppUserInfo,
+ UpdateAppInput,
+)
+
+if TYPE_CHECKING:
+ from posthog.api.routing import TeamAndOrgViewSetMixin
+ from posthog.models.user import User
+
+# --- Output Serializers ---
+
+
+class StreamlitAppUserSerializer(DataclassSerializer):
+ class Meta:
+ dataclass = StreamlitAppUserInfo
+
+
+class StreamlitAppVersionSerializer(DataclassSerializer):
+ created_by = StreamlitAppUserSerializer(
+ allow_null=True, required=False, help_text="User who uploaded this version."
+ )
+
+ class Meta:
+ dataclass = AppVersionContract
+
+
+class StreamlitAppSandboxSerializer(DataclassSerializer):
+ class Meta:
+ dataclass = AppSandboxContract
+
+
+class StreamlitAppMinimalSerializer(DataclassSerializer):
+ created_by = StreamlitAppUserSerializer(allow_null=True, required=False, help_text="User who created this app.")
+
+ class Meta:
+ dataclass = AppContract
+ exclude = ["active_version", "sandbox"]
+
+
+class StreamlitAppSerializer(DataclassSerializer):
+ created_by = StreamlitAppUserSerializer(allow_null=True, required=False, help_text="User who created this app.")
+ active_version = StreamlitAppVersionSerializer(
+ allow_null=True, required=False, help_text="Currently active version, or null if none uploaded yet."
+ )
+ sandbox = StreamlitAppSandboxSerializer(
+ allow_null=True, required=False, help_text="Current sandbox state, or null if the app has never started."
+ )
+
+ class Meta:
+ dataclass = AppContract
+
+
+# --- Input Serializers ---
+
+
+class CreateAppInputSerializer(DataclassSerializer):
+ name = serializers.CharField(help_text="Name of the app.")
+ description = serializers.CharField(required=False, allow_blank=True, help_text="Optional description of the app.")
+ cpu_cores = serializers.FloatField(required=False, help_text="CPU cores allocated to the sandbox.")
+ memory_gb = serializers.FloatField(required=False, help_text="Memory in GB allocated to the sandbox.")
+
+ class Meta:
+ dataclass = CreateAppInput
+
+
+class UpdateAppInputSerializer(DataclassSerializer):
+ name = serializers.CharField(required=False, help_text="New name for the app.")
+ description = serializers.CharField(required=False, allow_blank=True, help_text="New description for the app.")
+ cpu_cores = serializers.FloatField(required=False, help_text="New CPU core allocation for the sandbox.")
+ memory_gb = serializers.FloatField(required=False, help_text="New memory (GB) allocation for the sandbox.")
+
+ class Meta:
+ dataclass = UpdateAppInput
+
+
+class StreamlitAppStatusSerializer(serializers.Serializer):
+ status = serializers.CharField(help_text="Sandbox lifecycle status, or 'stopped' when no sandbox exists.")
+ restart_count = serializers.IntegerField(help_text="Number of times the app's sandbox has been restarted.")
+ last_error = serializers.CharField(
+ allow_blank=True, help_text="Most recent sandbox error message, empty when there is none."
+ )
+ started_at = serializers.DateTimeField(
+ allow_null=True, help_text="When the current sandbox started, null when stopped."
+ )
+ last_activity_at = serializers.DateTimeField(
+ allow_null=True, help_text="Timestamp of the last recorded viewer activity, null when none."
+ )
+ version_number = serializers.IntegerField(
+ allow_null=True, required=False, help_text="Version number the running sandbox was booted from."
+ )
+
+
+class StreamlitAppVersionListSerializer(serializers.Serializer):
+ results = StreamlitAppVersionSerializer(
+ many=True, help_text="Most recent versions of the app, newest first (capped at 50)."
+ )
+
+
+class ActivateVersionRequestSerializer(serializers.Serializer):
+ version_number = serializers.IntegerField(
+ help_text="Version number to activate. Must reference an existing version of this app."
+ )
+
+
+class ActivateVersionResponseSerializer(serializers.Serializer):
+ active_version = StreamlitAppVersionSerializer(help_text="The version that is now active for the app.")
+
+
+class UploadVersionRequestSerializer(serializers.Serializer):
+ file = serializers.FileField(help_text="Zip archive containing the Streamlit app sources (max 10 MB).")
+
+
+class StreamlitConnectInfoSerializer(serializers.Serializer):
+ iframe_url = serializers.CharField(help_text="Authenticated URL to embed the running app in an iframe.")
+ expires_in = serializers.IntegerField(help_text="Seconds until the embedded session credential expires.")
+
+
+def streamlit_apps_flag_enabled(distinct_id: str, organization_id: str) -> bool:
+ return bool(
+ posthoganalytics.feature_enabled(
+ "streamlit-apps",
+ distinct_id,
+ groups={"organization": organization_id},
+ group_properties={"organization": {"id": organization_id}},
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+ )
+
+
+class StreamlitAppsAccessPermission(BasePermission):
+ message = "Streamlit apps is not available."
+
+ def has_permission(self, request: Request, view: APIView) -> bool:
+ user = request.user
+ if not user or not user.is_authenticated:
+ return False
+ organization = cast("TeamAndOrgViewSetMixin", view).organization
+ distinct_id = cast("User", user).distinct_id or str(organization.id)
+ return streamlit_apps_flag_enabled(distinct_id, str(organization.id))
diff --git a/products/streamlit_apps/backend/presentation/views.py b/products/streamlit_apps/backend/presentation/views.py
new file mode 100644
index 000000000000..3851ffdad1e8
--- /dev/null
+++ b/products/streamlit_apps/backend/presentation/views.py
@@ -0,0 +1,291 @@
+from typing import Any, cast
+
+from django.core.cache import cache
+
+import structlog
+from drf_spectacular.utils import OpenApiResponse, extend_schema
+from loginas.utils import is_impersonated_session
+from rest_framework import status, viewsets
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.api.mixins import TypedRequest, validated_request
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.api.utils import action
+from posthog.models.user import User
+from posthog.rate_limit import ClickHouseBurstRateThrottle
+
+from products.streamlit_apps.backend.facade import api
+from products.streamlit_apps.backend.facade.contracts import CreateAppInput, UpdateAppInput
+from products.streamlit_apps.backend.presentation.serializers import (
+ ActivateVersionRequestSerializer,
+ ActivateVersionResponseSerializer,
+ CreateAppInputSerializer,
+ StreamlitAppMinimalSerializer,
+ StreamlitAppsAccessPermission,
+ StreamlitAppSandboxSerializer,
+ StreamlitAppSerializer,
+ StreamlitAppStatusSerializer,
+ StreamlitAppVersionListSerializer,
+ StreamlitAppVersionSerializer,
+ StreamlitConnectInfoSerializer,
+ UpdateAppInputSerializer,
+ UploadVersionRequestSerializer,
+)
+
+logger = structlog.get_logger(__name__)
+
+_STATUS_CACHE_TTL_SECONDS = 2
+
+
+class StreamlitAppViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ scope_object = "streamlit_app"
+ permission_classes = [StreamlitAppsAccessPermission]
+ lookup_field = "short_id"
+
+ @extend_schema(summary="List streamlit apps", responses={200: StreamlitAppMinimalSerializer(many=True)})
+ def list(self, request: Request, **kwargs: Any) -> Response:
+ apps = api.list_apps(self.team_id)
+ page = self.paginate_queryset(apps)
+ if page is not None:
+ return self.get_paginated_response(StreamlitAppMinimalSerializer(page, many=True).data)
+ return Response(StreamlitAppMinimalSerializer(apps, many=True).data)
+
+ @validated_request(
+ request_serializer=CreateAppInputSerializer,
+ summary="Create a streamlit app",
+ responses={201: OpenApiResponse(response=StreamlitAppSerializer)},
+ )
+ def create(self, request: TypedRequest[CreateAppInput], **kwargs: Any) -> Response:
+ try:
+ app = api.create_app(
+ team_id=self.team_id,
+ user=cast(User, request.user),
+ data=request.validated_data,
+ was_impersonated=is_impersonated_session(request),
+ )
+ except ValueError as e:
+ return Response({"detail": str(e)}, status=status.HTTP_400_BAD_REQUEST)
+ return Response(StreamlitAppSerializer(app).data, status=status.HTTP_201_CREATED)
+
+ @extend_schema(summary="Retrieve a streamlit app", responses={200: StreamlitAppSerializer})
+ def retrieve(self, request: Request, short_id: str, **kwargs: Any) -> Response:
+ try:
+ app = api.get_app(self.team_id, short_id)
+ except api.AppNotFoundError:
+ return Response(status=status.HTTP_404_NOT_FOUND)
+ return Response(StreamlitAppSerializer(app).data)
+
+ def _update(self, request: TypedRequest[UpdateAppInput], short_id: str) -> Response:
+ try:
+ app = api.update_app(
+ team_id=self.team_id,
+ short_id=short_id,
+ user=cast(User, request.user),
+ data=request.validated_data,
+ was_impersonated=is_impersonated_session(request),
+ )
+ except api.AppNotFoundError:
+ return Response(status=status.HTTP_404_NOT_FOUND)
+ except ValueError as e:
+ return Response({"detail": str(e)}, status=status.HTTP_400_BAD_REQUEST)
+ return Response(StreamlitAppSerializer(app).data)
+
+ @validated_request(
+ request_serializer=UpdateAppInputSerializer,
+ summary="Update a streamlit app",
+ responses={200: OpenApiResponse(response=StreamlitAppSerializer)},
+ )
+ def update(self, request: TypedRequest[UpdateAppInput], short_id: str, **kwargs: Any) -> Response:
+ return self._update(request, short_id)
+
+ @validated_request(
+ request_serializer=UpdateAppInputSerializer,
+ summary="Partially update a streamlit app",
+ responses={200: OpenApiResponse(response=StreamlitAppSerializer)},
+ )
+ def partial_update(self, request: TypedRequest[UpdateAppInput], short_id: str, **kwargs: Any) -> Response:
+ return self._update(request, short_id)
+
+ @extend_schema(summary="Delete a streamlit app", request=None, responses={204: None})
+ def destroy(self, request: Request, short_id: str, **kwargs: Any) -> Response:
+ try:
+ api.delete_app(
+ team_id=self.team_id,
+ short_id=short_id,
+ user=cast(User, request.user),
+ was_impersonated=is_impersonated_session(request),
+ )
+ except api.AppNotFoundError:
+ return Response(status=status.HTTP_404_NOT_FOUND)
+ return Response(status=status.HTTP_204_NO_CONTENT)
+
+ @extend_schema(
+ summary="List app versions",
+ responses={200: StreamlitAppVersionListSerializer},
+ )
+ @action(methods=["GET"], detail=True, url_path="versions")
+ def versions(self, request: Request, short_id: str, **kwargs: Any) -> Response:
+ try:
+ versions = api.list_versions(self.team_id, short_id)
+ except api.AppNotFoundError:
+ return Response(status=status.HTTP_404_NOT_FOUND)
+ return Response({"results": StreamlitAppVersionSerializer(versions, many=True).data})
+
+ @extend_schema(
+ summary="Upload a new app version",
+ request=UploadVersionRequestSerializer,
+ responses={201: StreamlitAppVersionSerializer},
+ )
+ @action(methods=["POST"], detail=True, url_path="upload_version")
+ def upload_version(self, request: Request, short_id: str, **kwargs: Any) -> Response:
+ zip_file = request.FILES.get("file")
+ if not zip_file:
+ return Response({"detail": "No file provided."}, status=status.HTTP_400_BAD_REQUEST)
+
+ # Reject oversized uploads by their declared size before reading the body
+ # into memory, so a large multipart POST can't force a full allocation.
+ try:
+ api.check_zip_size(zip_file.size)
+ except api.ZipTooLargeError as e:
+ return Response({"detail": str(e)}, status=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE)
+
+ file_content = zip_file.read()
+
+ try:
+ version = api.upload_version(
+ team_id=self.team_id,
+ short_id=short_id,
+ user=cast(User, request.user),
+ file_content=file_content,
+ declared_size=zip_file.size,
+ was_impersonated=is_impersonated_session(request),
+ )
+ except api.AppNotFoundError:
+ return Response(status=status.HTTP_404_NOT_FOUND)
+ except api.ZipTooLargeError as e:
+ return Response({"detail": str(e)}, status=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE)
+ except api.InvalidZipError as e:
+ return Response({"detail": str(e)}, status=status.HTTP_400_BAD_REQUEST)
+ except api.ConcurrentUploadError as e:
+ return Response({"detail": str(e)}, status=status.HTTP_409_CONFLICT)
+
+ return Response(StreamlitAppVersionSerializer(version).data, status=status.HTTP_201_CREATED)
+
+ @extend_schema(
+ summary="Activate an existing app version",
+ request=ActivateVersionRequestSerializer,
+ responses={200: ActivateVersionResponseSerializer},
+ )
+ @action(methods=["POST"], detail=True, url_path="activate_version")
+ def activate_version(self, request: Request, short_id: str, **kwargs: Any) -> Response:
+ version_number = request.data.get("version_number")
+
+ if version_number is None:
+ return Response({"detail": "version_number is required."}, status=status.HTTP_400_BAD_REQUEST)
+
+ # Guard the type before the facade call: a non-integer (e.g. "abc" or 1.5)
+ # would otherwise raise ValueError deep in the ORM and surface as a 500.
+ if not isinstance(version_number, int) or isinstance(version_number, bool):
+ return Response({"detail": "version_number must be an integer."}, status=status.HTTP_400_BAD_REQUEST)
+
+ try:
+ version = api.activate_version(
+ team_id=self.team_id,
+ short_id=short_id,
+ user=cast(User, request.user),
+ version_number=version_number,
+ was_impersonated=is_impersonated_session(request),
+ )
+ except api.AppNotFoundError:
+ return Response(status=status.HTTP_404_NOT_FOUND)
+ except api.VersionNotFoundError as e:
+ return Response({"detail": str(e)}, status=status.HTTP_404_NOT_FOUND)
+
+ return Response({"active_version": StreamlitAppVersionSerializer(version).data})
+
+ @extend_schema(
+ summary="Get app sandbox status",
+ responses={200: StreamlitAppStatusSerializer},
+ )
+ @action(methods=["GET"], detail=True, url_path="status")
+ def get_status(self, request: Request, short_id: str, **kwargs: Any) -> Response:
+ cache_key = f"streamlit_sandbox_status:{self.team_id}:{short_id}"
+ cached = cache.get(cache_key)
+ if cached is not None:
+ return Response(cached)
+
+ try:
+ sandbox = api.get_status(self.team_id, short_id)
+ except api.AppNotFoundError:
+ return Response(status=status.HTTP_404_NOT_FOUND)
+
+ payload = StreamlitAppSandboxSerializer(sandbox).data
+ cache.set(cache_key, payload, _STATUS_CACHE_TTL_SECONDS)
+ return Response(payload)
+
+ @extend_schema(
+ summary="Start the app sandbox",
+ request=None,
+ responses={200: StreamlitAppSerializer, 202: StreamlitAppSerializer},
+ )
+ @action(methods=["POST"], detail=True, url_path="start", throttle_classes=[ClickHouseBurstRateThrottle])
+ def start(self, request: Request, short_id: str, **kwargs: Any) -> Response:
+ try:
+ app, already_running = api.start_app(self.team_id, short_id)
+ except api.AppNotFoundError:
+ return Response(status=status.HTTP_404_NOT_FOUND)
+ except api.NoActiveVersionError as e:
+ return Response({"detail": str(e)}, status=status.HTTP_400_BAD_REQUEST)
+
+ if already_running:
+ return Response(StreamlitAppSerializer(app).data)
+ return Response(StreamlitAppSerializer(app).data, status=status.HTTP_202_ACCEPTED)
+
+ @extend_schema(
+ summary="Stop the app sandbox",
+ request=None,
+ responses={200: StreamlitAppSerializer},
+ )
+ @action(methods=["POST"], detail=True, url_path="stop")
+ def stop(self, request: Request, short_id: str, **kwargs: Any) -> Response:
+ try:
+ app = api.stop_app(self.team_id, short_id)
+ except api.AppNotFoundError:
+ return Response(status=status.HTTP_404_NOT_FOUND)
+ except Exception as e:
+ logger.exception("streamlit_app_stop_failed", short_id=short_id, error=str(e))
+ return Response({"detail": "Failed to stop app."}, status=status.HTTP_503_SERVICE_UNAVAILABLE)
+
+ return Response(StreamlitAppSerializer(app).data)
+
+ @extend_schema(
+ summary="Get iframe connection info for a running app",
+ responses={200: StreamlitConnectInfoSerializer},
+ )
+ @action(methods=["GET"], detail=True, url_path="connect_info", throttle_classes=[ClickHouseBurstRateThrottle])
+ def connect_info(self, request: Request, short_id: str, **kwargs: Any) -> Response:
+ try:
+ connect_info = api.get_connect_info(self.team_id, short_id, cast(User, request.user))
+ except api.AppNotFoundError:
+ return Response(status=status.HTTP_404_NOT_FOUND)
+ except api.AppNotRunningError as e:
+ return Response({"detail": str(e)}, status=status.HTTP_503_SERVICE_UNAVAILABLE)
+ except api.ConnectUnavailableError as e:
+ return Response({"detail": str(e)}, status=status.HTTP_502_BAD_GATEWAY)
+
+ return Response(StreamlitConnectInfoSerializer(connect_info).data)
+
+ @extend_schema(
+ summary="Restart the app sandbox",
+ request=None,
+ responses={202: StreamlitAppSerializer},
+ )
+ @action(methods=["POST"], detail=True, url_path="restart", throttle_classes=[ClickHouseBurstRateThrottle])
+ def restart(self, request: Request, short_id: str, **kwargs: Any) -> Response:
+ try:
+ app, _transitioning = api.restart_app(self.team_id, short_id)
+ except api.AppNotFoundError:
+ return Response(status=status.HTTP_404_NOT_FOUND)
+
+ return Response(StreamlitAppSerializer(app).data, status=status.HTTP_202_ACCEPTED)
diff --git a/products/streamlit_apps/backend/routes.py b/products/streamlit_apps/backend/routes.py
new file mode 100644
index 000000000000..ab5a5147a865
--- /dev/null
+++ b/products/streamlit_apps/backend/routes.py
@@ -0,0 +1,7 @@
+from posthog.api.routing import RouterRegistry
+
+from products.streamlit_apps.backend.presentation.views import StreamlitAppViewSet
+
+
+def register_routes(routers: RouterRegistry) -> None:
+ routers.projects.register(r"streamlit_apps", StreamlitAppViewSet, "project_streamlit_apps", ["team_id"])
diff --git a/products/streamlit_apps/backend/tasks/tasks.py b/products/streamlit_apps/backend/tasks/tasks.py
index c842ec746375..eee2cd64ab5c 100644
--- a/products/streamlit_apps/backend/tasks/tasks.py
+++ b/products/streamlit_apps/backend/tasks/tasks.py
@@ -237,7 +237,7 @@ def stop_idle_streamlit_sandboxes() -> int:
def auto_restart_crashed_streamlit_sandboxes() -> int:
"""Restart sandboxes that died on their own (Modal TTL timeout), respecting
the MAX_RESTART_COUNT cap. Only acts on the exact `last_error` set by
- `_sync_sandbox_status` — user-initiated stops, idle stops, and startup
+ `sync_sandbox_status` — user-initiated stops, idle stops, and startup
failures leave a different string and are not restarted."""
from products.streamlit_apps.backend.logic.app_runtime import MAX_RESTART_COUNT, TTL_TIMEOUT_LAST_ERROR
from products.streamlit_apps.backend.models import StreamlitAppSandbox
diff --git a/products/streamlit_apps/backend/tests/test_app_runtime.py b/products/streamlit_apps/backend/tests/test_app_runtime.py
index 39b9cb27ec6e..e34a990f9d5e 100644
--- a/products/streamlit_apps/backend/tests/test_app_runtime.py
+++ b/products/streamlit_apps/backend/tests/test_app_runtime.py
@@ -506,11 +506,11 @@ class TestResetRestartCountIfStable(BaseTest):
class TestSyncSandboxStatus(BaseTest):
- """_sync_sandbox_status must never promote STARTING → RUNNING — that
+ """sync_sandbox_status must never promote STARTING → RUNNING — that
path is reserved for start_app after both readiness probes pass."""
def test_sync_does_not_promote_starting_to_running(self):
- from products.streamlit_apps.backend.logic.app_runtime import _sync_sandbox_status
+ from products.streamlit_apps.backend.logic.app_runtime import sync_sandbox_status
app = StreamlitApp.objects.create(team=self.team, name="T")
version = StreamlitAppVersion.objects.create(app=app, version_number=1, zip_file="a.zip", zip_hash="a")
@@ -525,17 +525,17 @@ class TestSyncSandboxStatus(BaseTest):
mock_sandbox = MagicMock()
mock_sandbox.is_running.return_value = True
mock_cls.return_value.get_by_id.return_value = mock_sandbox
- result = _sync_sandbox_status(sandbox_record)
+ result = sync_sandbox_status(sandbox_record)
assert result.status == StreamlitAppSandbox.Status.STARTING
def test_sync_expires_stuck_starting_to_error(self):
- from products.streamlit_apps.backend.logic.app_runtime import STARTING_TIMEOUT_SECONDS, _sync_sandbox_status
+ from products.streamlit_apps.backend.logic.app_runtime import STARTING_TIMEOUT_SECONDS, sync_sandbox_status
app = StreamlitApp.objects.create(team=self.team, name="T")
version = StreamlitAppVersion.objects.create(app=app, version_number=1, zip_file="a.zip", zip_hash="a")
# Backdate started_at past the startup budget: started_at is the
- # reference _sync_sandbox_status uses for the STARTING age check,
+ # reference sync_sandbox_status uses for the STARTING age check,
# and start_app stamps it on every new attempt.
sandbox_record = StreamlitAppSandbox.objects.create(
app=app,
@@ -545,7 +545,7 @@ class TestSyncSandboxStatus(BaseTest):
started_at=timezone.now() - timedelta(seconds=STARTING_TIMEOUT_SECONDS + 10),
)
- result = _sync_sandbox_status(sandbox_record)
+ result = sync_sandbox_status(sandbox_record)
assert result.status == StreamlitAppSandbox.Status.ERROR
assert "timed out" in result.last_error.lower()
@@ -556,7 +556,7 @@ class TestSyncSandboxStatus(BaseTest):
attempt must NOT be marked as timed out — the age check uses
started_at which tracks this particular attempt.
"""
- from products.streamlit_apps.backend.logic.app_runtime import STARTING_TIMEOUT_SECONDS, _sync_sandbox_status
+ from products.streamlit_apps.backend.logic.app_runtime import STARTING_TIMEOUT_SECONDS, sync_sandbox_status
app = StreamlitApp.objects.create(team=self.team, name="T")
version = StreamlitAppVersion.objects.create(app=app, version_number=1, zip_file="a.zip", zip_hash="a")
@@ -575,7 +575,7 @@ class TestSyncSandboxStatus(BaseTest):
)
sandbox_record.refresh_from_db()
- result = _sync_sandbox_status(sandbox_record)
+ result = sync_sandbox_status(sandbox_record)
assert result.status == StreamlitAppSandbox.Status.STARTING
assert result.last_error == ""
diff --git a/products/streamlit_apps/backend/tests/test_bridge.py b/products/streamlit_apps/backend/tests/test_bridge.py
index 1cda57224c1d..e285b7594163 100644
--- a/products/streamlit_apps/backend/tests/test_bridge.py
+++ b/products/streamlit_apps/backend/tests/test_bridge.py
@@ -1,8 +1,15 @@
+import json
+
import pytest
-from posthog.test.base import BaseTest
-from unittest.mock import MagicMock, patch
+from posthog.test.base import APIBaseTest, BaseTest
+from unittest.mock import patch
+
+from parameterized import parameterized
+
+from posthog.schema import HogQLQueryResponse
from products.streamlit_apps.backend.logic.bridge import execute_bridge_query
+from products.streamlit_apps.backend.tests.test_presentation import _StreamlitAppsFlagMixin
class TestExecuteBridgeQuery(BaseTest):
@@ -10,33 +17,26 @@ class TestExecuteBridgeQuery(BaseTest):
def test_returns_whitelisted_response(self, mock_execute):
"""Only the columns/results/types fields are surfaced — clickhouse SQL,
hogql AST, internal timings, and modifiers must NOT leak through."""
- response = MagicMock()
- response.model_dump.return_value = {
- "results": [[1, "hello"]],
- "columns": ["id", "name"],
- "clickhouse": "SELECT ...",
- "hogql": "SELECT ...",
- "timings": {"total": 0.1},
- "modifiers": {},
- "types": [["Int64"], ["String"]],
- }
- mock_execute.return_value = response
+ # A fully-populated response: the internal fields (clickhouse SQL, hogql AST)
+ # are present on the object and must still not reach the caller.
+ mock_execute.return_value = HogQLQueryResponse(
+ results=[[1, "hello"]],
+ columns=["id", "name"],
+ types=[["Int64"], ["String"]],
+ hogql="SELECT ...",
+ clickhouse="SELECT ...",
+ )
result = execute_bridge_query(query="SELECT 1", team_id=self.team.id)
+ assert set(result.keys()) == {"columns", "results", "types"}
assert result["results"] == [[1, "hello"]]
assert result["columns"] == ["id", "name"]
assert result["types"] == [["Int64"], ["String"]]
- assert "clickhouse" not in result
- assert "hogql" not in result
- assert "timings" not in result
- assert "modifiers" not in result
@patch("products.streamlit_apps.backend.logic.bridge.execute_hogql_query")
def test_passes_query_and_team(self, mock_execute):
- response = MagicMock()
- response.model_dump.return_value = {"results": [], "columns": []}
- mock_execute.return_value = response
+ mock_execute.return_value = HogQLQueryResponse(results=[], columns=[])
execute_bridge_query(query="SELECT event FROM events", team_id=self.team.id)
@@ -48,3 +48,270 @@ class TestExecuteBridgeQuery(BaseTest):
def test_invalid_team_raises(self):
with pytest.raises(Exception):
execute_bridge_query(query="SELECT 1", team_id=999999)
+
+
+class TestStreamlitBridgeView(_StreamlitAppsFlagMixin, APIBaseTest):
+ def _url(self):
+ return "/api/streamlit_bridge/query/"
+
+ def _streamlit_token(self) -> str:
+ """Mint a bridge-scoped token. Iframe-scoped tokens are refused by the
+ bridge, so happy-path bridge tests must mint the bridge variant."""
+ from products.streamlit_apps.backend.logic.oauth import create_sandbox_bridge_token
+
+ return create_sandbox_bridge_token(user=self.user, team_id=self.team.id)
+
+ @parameterized.expand(
+ [
+ ("missing_header", {}, None, 401, "Missing or invalid Authorization header"),
+ ("bad_prefix", {}, "Token abc", 401, "Missing or invalid Authorization header"),
+ ]
+ )
+ def test_auth_failures(self, _name, body, auth_value, expected_status, expected_error):
+ headers = {}
+ if auth_value:
+ headers["HTTP_AUTHORIZATION"] = auth_value
+ response = self.client.post(
+ self._url(),
+ data=json.dumps(body),
+ content_type="application/json",
+ **headers,
+ )
+ assert response.status_code == expected_status
+ assert expected_error in response.json()["error"]
+
+ def test_garbage_token_rejected(self):
+ response = self.client.post(
+ self._url(),
+ data=json.dumps({"query": "SELECT 1"}),
+ content_type="application/json",
+ HTTP_AUTHORIZATION="Bearer not-a-real-token",
+ )
+ assert response.status_code == 401
+
+ def test_inactive_user_token_rejected(self):
+ # A bridge token outlives the minting user, so deactivating the user must
+ # immediately revoke the sandbox's access to team data.
+ token = self._streamlit_token()
+ self.user.is_active = False
+ self.user.save()
+
+ response = self.client.post(
+ self._url(),
+ data=json.dumps({"query": "SELECT 1"}),
+ content_type="application/json",
+ HTTP_AUTHORIZATION=f"Bearer {token}",
+ )
+ assert response.status_code == 401
+
+ def test_non_member_user_token_rejected(self):
+ # A token whose user no longer belongs to the scoped team's organization
+ # must not grant query access, even with a valid bridge scope.
+ from posthog.models import Organization, User
+
+ from products.streamlit_apps.backend.logic.oauth import create_sandbox_bridge_token
+
+ other_org = Organization.objects.create(name="Outsider Org")
+ outsider = User.objects.create_and_join(other_org, "[email protected]", None)
+ token = create_sandbox_bridge_token(user=outsider, team_id=self.team.id)
+
+ response = self.client.post(
+ self._url(),
+ data=json.dumps({"query": "SELECT 1"}),
+ content_type="application/json",
+ HTTP_AUTHORIZATION=f"Bearer {token}",
+ )
+ assert response.status_code == 401
+
+ def test_invalid_json_body(self):
+ response = self.client.post(
+ self._url(),
+ data="not json",
+ content_type="application/json",
+ HTTP_AUTHORIZATION=f"Bearer {self._streamlit_token()}",
+ )
+ assert response.status_code == 400
+ assert "Invalid JSON" in response.json()["error"]
+
+ @parameterized.expand(
+ [
+ ("missing_query", {}),
+ ("empty_query", {"query": ""}),
+ ("query_is_number", {"query": 123}),
+ ("query_whitespace_only", {"query": " "}),
+ ]
+ )
+ def test_invalid_query_field(self, _name, body):
+ response = self.client.post(
+ self._url(),
+ data=json.dumps(body),
+ content_type="application/json",
+ HTTP_AUTHORIZATION=f"Bearer {self._streamlit_token()}",
+ )
+ assert response.status_code == 400
+ assert "query" in response.json()["error"].lower()
+
+ @patch("products.streamlit_apps.backend.logic.bridge.execute_hogql_query")
+ def test_successful_query_with_oauth(self, mock_execute):
+ mock_execute.return_value = HogQLQueryResponse(
+ results=[[1, "test"]],
+ columns=["id", "name"],
+ hogql="SELECT ...",
+ clickhouse="SELECT ...",
+ )
+
+ response = self.client.post(
+ self._url(),
+ data=json.dumps({"query": "SELECT id, name FROM persons"}),
+ content_type="application/json",
+ HTTP_AUTHORIZATION=f"Bearer {self._streamlit_token()}",
+ )
+ assert response.status_code == 200
+ data = response.json()
+ assert data["results"] == [[1, "test"]]
+ assert data["columns"] == ["id", "name"]
+ assert "clickhouse" not in data
+
+ @patch("products.streamlit_apps.backend.logic.bridge.execute_hogql_query")
+ def test_query_execution_error_returns_400(self, mock_execute):
+ mock_execute.side_effect = Exception("Parse error near 'SELCT'")
+
+ response = self.client.post(
+ self._url(),
+ data=json.dumps({"query": "SELCT bad"}),
+ content_type="application/json",
+ HTTP_AUTHORIZATION=f"Bearer {self._streamlit_token()}",
+ )
+ assert response.status_code == 400
+ assert "error" in response.json()
+
+ def test_expired_oauth_token_rejected(self):
+ from datetime import timedelta
+
+ from django.utils import timezone
+
+ from posthog.models.oauth import OAuthAccessToken
+ from posthog.models.utils import generate_random_oauth_access_token
+
+ from products.streamlit_apps.backend.logic.oauth import BRIDGE_TOKEN_SCOPE, get_streamlit_oauth_app
+
+ oauth_app = get_streamlit_oauth_app()
+ token_value = generate_random_oauth_access_token(None)
+ OAuthAccessToken.objects.create(
+ application=oauth_app,
+ token=token_value,
+ user=self.user,
+ expires=timezone.now() - timedelta(hours=1),
+ scope=BRIDGE_TOKEN_SCOPE,
+ scoped_teams=[self.team.id],
+ )
+
+ response = self.client.post(
+ self._url(),
+ data=json.dumps({"query": "SELECT 1"}),
+ content_type="application/json",
+ HTTP_AUTHORIZATION=f"Bearer {token_value}",
+ )
+ assert response.status_code == 401
+ assert "expired" in response.json()["error"].lower()
+
+ def test_iframe_scoped_token_rejected(self):
+ """Iframe tokens (carrying `streamlit:iframe`) must not work as bridge
+ credentials even though they're in the same OAuth application. This is
+ the other half of the iframe-vs-bridge scope split."""
+ from products.streamlit_apps.backend.logic.oauth import create_streamlit_access_token
+
+ iframe_token = create_streamlit_access_token(user=self.user, team_id=self.team.id)
+
+ response = self.client.post(
+ self._url(),
+ data=json.dumps({"query": "SELECT 1"}),
+ content_type="application/json",
+ HTTP_AUTHORIZATION=f"Bearer {iframe_token.token}",
+ )
+ assert response.status_code == 401
+
+ def test_multi_team_token_rejected(self):
+ """Bridge tokens must be scoped to exactly one team — picking the
+ first team from a multi-team list would let a token minted for team A
+ silently run queries against team B."""
+ from datetime import timedelta
+
+ from django.utils import timezone
+
+ from posthog.models.oauth import OAuthAccessToken
+ from posthog.models.utils import generate_random_oauth_access_token
+
+ from products.streamlit_apps.backend.logic.oauth import BRIDGE_TOKEN_SCOPE, get_streamlit_oauth_app
+
+ # Two teams, one token — the bridge should refuse even though the
+ # correct team is in the list.
+ other_team_id = self.team.id + 9999
+ token_value = generate_random_oauth_access_token(None)
+ OAuthAccessToken.objects.create(
+ application=get_streamlit_oauth_app(),
+ token=token_value,
+ user=self.user,
+ expires=timezone.now() + timedelta(hours=1),
+ scope=BRIDGE_TOKEN_SCOPE,
+ scoped_teams=[self.team.id, other_team_id],
+ )
+
+ response = self.client.post(
+ self._url(),
+ data=json.dumps({"query": "SELECT 1"}),
+ content_type="application/json",
+ HTTP_AUTHORIZATION=f"Bearer {token_value}",
+ )
+ assert response.status_code == 401
+ assert "exactly one team" in response.json()["error"].lower()
+
+ def test_oauth_token_from_other_application_rejected(self):
+ """A token minted against any non-streamlit OAuth app must be rejected
+ even if it carries the streamlit:bridge scope and a valid scoped_teams."""
+ from datetime import timedelta
+
+ from django.utils import timezone
+
+ from posthog.models.oauth import OAuthAccessToken, OAuthApplication
+ from posthog.models.utils import generate_random_oauth_access_token
+
+ from products.streamlit_apps.backend.logic.oauth import BRIDGE_TOKEN_SCOPE
+
+ other_app = OAuthApplication.objects.create(
+ name="Some Other App",
+ client_type="confidential",
+ authorization_grant_type="authorization-code",
+ redirect_uris="https://localhost",
+ algorithm="RS256",
+ is_first_party=True,
+ )
+ token_value = generate_random_oauth_access_token(None)
+ OAuthAccessToken.objects.create(
+ application=other_app,
+ token=token_value,
+ user=self.user,
+ expires=timezone.now() + timedelta(hours=1),
+ scope=BRIDGE_TOKEN_SCOPE,
+ scoped_teams=[self.team.id],
+ )
+
+ response = self.client.post(
+ self._url(),
+ data=json.dumps({"query": "SELECT 1"}),
+ content_type="application/json",
+ HTTP_AUTHORIZATION=f"Bearer {token_value}",
+ )
+ assert response.status_code == 401
+ assert "application" in response.json()["error"].lower()
+
+ def test_flag_disabled_returns_403(self):
+ self._set_streamlit_apps_flag(False)
+ response = self.client.post(
+ self._url(),
+ data=json.dumps({"query": "SELECT 1"}),
+ content_type="application/json",
+ HTTP_AUTHORIZATION=f"Bearer {self._streamlit_token()}",
+ )
+ assert response.status_code == 403
+ assert "not available" in response.json()["error"]
diff --git a/products/streamlit_apps/backend/tests/test_presentation.py b/products/streamlit_apps/backend/tests/test_presentation.py
new file mode 100644
index 000000000000..2586df5f0eb2
--- /dev/null
+++ b/products/streamlit_apps/backend/tests/test_presentation.py
@@ -0,0 +1,682 @@
+import io
+import uuid
+import zipfile
+from typing import Any
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import MagicMock, patch
+
+from django.utils import timezone
+
+from parameterized import parameterized
+from rest_framework import status
+
+from products.streamlit_apps.backend.models import StreamlitApp, StreamlitAppSandbox, StreamlitAppVersion
+
+
+def _make_zip(files: dict[str, str]) -> bytes:
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as zf:
+ for name, content in files.items():
+ zf.writestr(name, content)
+ return buf.getvalue()
+
+
+VALID_ZIP = _make_zip({"app.py": "import streamlit as st\nst.title('Hello')"})
+ZIP_WITH_REQUIREMENTS = _make_zip(
+ {
+ "app.py": "import streamlit as st",
+ "requirements.txt": "pandas\nnumpy\n",
+ }
+)
+
+
+class _StreamlitAppsFlagMixin:
+ """Shared test setup that mocks the `streamlit-apps` feature flag.
+
+ StreamlitAppsAccessPermission hides the whole viewset behind the flag,
+ so every test class that talks to the viewset needs to opt in. Default
+ every test to "flag enabled" so the existing assertions keep working;
+ the one flag-gating test flips it back off explicitly.
+ """
+
+ _flag_patcher: Any
+
+ def setUp(self):
+ super().setUp() # type: ignore[misc]
+ self._set_streamlit_apps_flag(True)
+
+ def tearDown(self):
+ if hasattr(self, "_flag_patcher"):
+ self._flag_patcher.stop()
+ super().tearDown() # type: ignore[misc]
+
+ def _set_streamlit_apps_flag(self, enabled: bool) -> None:
+ if hasattr(self, "_flag_patcher"):
+ self._flag_patcher.stop()
+ self._flag_patcher = patch("posthoganalytics.feature_enabled")
+ mock = self._flag_patcher.start()
+
+ def check_flag(flag_name, *_args, **_kwargs):
+ # Match ONLY the streamlit-apps flag: returning True for all flag
+ # names would spuriously enable unrelated flags that other code
+ # in the stack evaluates during the same request.
+ if flag_name == "streamlit-apps":
+ return enabled
+ return False
+
+ mock.side_effect = check_flag
+
+
+class TestStreamlitAppAPI(_StreamlitAppsFlagMixin, APIBaseTest):
+ # The viewset is registered under /projects/ via the product's routes.py.
+ def _url(self, suffix: str = "") -> str:
+ base = f"/api/projects/{self.team.id}/streamlit_apps"
+ if suffix:
+ return f"{base}/{suffix}"
+ return f"{base}/"
+
+ def _create_app(self, **kwargs) -> StreamlitApp:
+ defaults = {"team": self.team, "name": "Test App", "created_by": self.user}
+ defaults.update(kwargs)
+ return StreamlitApp.objects.create(**defaults)
+
+ def _create_version(self, app: StreamlitApp, version_number: int = 1, **kwargs) -> StreamlitAppVersion:
+ defaults = {
+ "app": app,
+ "version_number": version_number,
+ "zip_file": f"streamlit_apps/{app.team_id}/{app.id}/v{version_number}.zip",
+ "zip_hash": "abc123",
+ "created_by": self.user,
+ }
+ defaults.update(kwargs)
+ return StreamlitAppVersion.objects.create(**defaults)
+
+ def test_list_apps_empty(self):
+ response = self.client.get(self._url())
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["results"] == []
+
+ def test_list_apps(self):
+ self._create_app(name="App A")
+ self._create_app(name="App B")
+ response = self.client.get(self._url())
+ assert response.status_code == status.HTTP_200_OK
+ assert len(response.json()["results"]) == 2
+
+ def test_list_excludes_deleted(self):
+ self._create_app(name="Visible")
+ self._create_app(name="Deleted", deleted=True)
+ response = self.client.get(self._url())
+ assert len(response.json()["results"]) == 1
+ assert response.json()["results"][0]["name"] == "Visible"
+
+ def test_list_excludes_other_teams(self):
+ from posthog.models import Organization, Team
+
+ other_org = Organization.objects.create(name="Other Org")
+ other_team = Team.objects.create(organization=other_org, name="Other Team")
+ self._create_app(name="My App")
+ StreamlitApp.objects.create(team=other_team, name="Other App")
+
+ response = self.client.get(self._url())
+ assert len(response.json()["results"]) == 1
+ assert response.json()["results"][0]["name"] == "My App"
+
+ def test_list_has_status(self):
+ app = self._create_app()
+ version = self._create_version(app)
+ StreamlitAppSandbox.objects.create(app=app, version=version, sandbox_id="sb_123", status="running")
+ response = self.client.get(self._url())
+ result = response.json()["results"][0]
+ assert result["status"] == "running"
+
+ def test_list_returns_403_when_feature_flag_disabled(self):
+ # StreamlitAppsAccessPermission hides the whole viewset behind the
+ # `streamlit-apps` PostHog flag; when the flag is off, even listing
+ # should 403 regardless of team membership.
+ self._set_streamlit_apps_flag(False)
+ response = self.client.get(self._url())
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+
+ def test_list_stopped_status_when_no_sandbox(self):
+ self._create_app()
+ response = self.client.get(self._url())
+ result = response.json()["results"][0]
+ assert result["status"] == "stopped"
+
+ def test_create_app(self):
+ response = self.client.post(self._url(), data={"name": "New App", "description": "A new app"})
+ assert response.status_code == status.HTTP_201_CREATED
+ data = response.json()
+ assert data["name"] == "New App"
+ assert data["description"] == "A new app"
+ assert data["short_id"]
+ assert data["created_by"]["id"] == self.user.id
+
+ def test_create_app_name_required(self):
+ response = self.client.post(self._url(), data={"description": "No name"})
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ @parameterized.expand(
+ [
+ ("custom_cpu", {"name": "App", "cpu_cores": 2.0}, "cpu_cores", 2.0),
+ ("custom_memory", {"name": "App", "memory_gb": 4.0}, "memory_gb", 4.0),
+ ("default_cpu", {"name": "App"}, "cpu_cores", 0.5),
+ ("default_memory", {"name": "App"}, "memory_gb", 1.0),
+ ]
+ )
+ def test_create_app_resource_config(self, _name, data, field, expected):
+ response = self.client.post(self._url(), data=data)
+ assert response.status_code == status.HTTP_201_CREATED
+ assert response.json()[field] == expected
+
+ def test_retrieve_app(self):
+ app = self._create_app(name="Detail App", description="Details here")
+ response = self.client.get(self._url(f"{app.short_id}/"))
+ assert response.status_code == status.HTTP_200_OK
+ data = response.json()
+ assert data["name"] == "Detail App"
+ assert data["description"] == "Details here"
+ assert "active_version" in data
+ assert "sandbox" in data
+
+ def test_retrieve_deleted_app_404(self):
+ app = self._create_app(deleted=True)
+ response = self.client.get(self._url(f"{app.short_id}/"))
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+
+ def test_update_app(self):
+ app = self._create_app(name="Old Name")
+ response = self.client.patch(self._url(f"{app.short_id}/"), data={"name": "New Name"})
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["name"] == "New Name"
+ app.refresh_from_db()
+ assert app.name == "New Name"
+
+ def test_update_cannot_change_short_id(self):
+ app = self._create_app()
+ original_short_id = app.short_id
+ self.client.patch(self._url(f"{app.short_id}/"), data={"short_id": "hacked"})
+ app.refresh_from_db()
+ assert app.short_id == original_short_id
+
+ def test_delete_app_soft_deletes(self):
+ app = self._create_app()
+ response = self.client.delete(self._url(f"{app.short_id}/"))
+ assert response.status_code == status.HTTP_204_NO_CONTENT
+ app.refresh_from_db()
+ assert app.deleted is True
+ assert app.deleted_at is not None
+
+ def test_deleted_app_not_in_list(self):
+ app = self._create_app()
+ self.client.delete(self._url(f"{app.short_id}/"))
+ response = self.client.get(self._url())
+ assert len(response.json()["results"]) == 0
+
+
+class TestStreamlitAppVersionAPI(_StreamlitAppsFlagMixin, APIBaseTest):
+ def _url(self, short_id: str, suffix: str = "") -> str:
+ base = f"/api/projects/{self.team.id}/streamlit_apps/{short_id}"
+ if suffix:
+ return f"{base}/{suffix}"
+ return f"{base}/"
+
+ def _create_app(self, **kwargs) -> StreamlitApp:
+ defaults = {"team": self.team, "name": "Test App", "created_by": self.user}
+ defaults.update(kwargs)
+ return StreamlitApp.objects.create(**defaults)
+
+ def _create_version(self, app: StreamlitApp, version_number: int = 1) -> StreamlitAppVersion:
+ return StreamlitAppVersion.objects.create(
+ app=app,
+ version_number=version_number,
+ zip_file=f"test/{app.id}/v{version_number}.zip",
+ zip_hash="abc",
+ created_by=self.user,
+ )
+
+ def test_list_versions_empty(self):
+ app = self._create_app()
+ response = self.client.get(self._url(app.short_id, "versions/"))
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["results"] == []
+
+ def test_list_versions_ordered_by_version_number_desc(self):
+ app = self._create_app()
+ self._create_version(app, 1)
+ self._create_version(app, 2)
+ self._create_version(app, 3)
+ response = self.client.get(self._url(app.short_id, "versions/"))
+ versions = response.json()["results"]
+ assert [v["version_number"] for v in versions] == [3, 2, 1]
+
+ @patch("posthog.storage.object_storage.write")
+ def test_upload_version_with_requirements_silently_accepted(self, mock_storage_write):
+ app = self._create_app()
+
+ from django.core.files.uploadedfile import SimpleUploadedFile
+
+ zip_file = SimpleUploadedFile("app.zip", ZIP_WITH_REQUIREMENTS, content_type="application/zip")
+ response = self.client.post(
+ self._url(app.short_id, "upload_version/"),
+ data={"file": zip_file},
+ format="multipart",
+ )
+ assert response.status_code == status.HTTP_201_CREATED
+ data = response.json()
+ assert data["version_number"] == 1
+ mock_storage_write.assert_called_once()
+
+ app.refresh_from_db()
+ assert app.active_version_id == uuid.UUID(data["id"])
+
+ @patch("posthog.storage.object_storage.write")
+ def test_upload_version_increments_number(self, mock_storage_write):
+ app = self._create_app()
+ self._create_version(app, 1)
+
+ from django.core.files.uploadedfile import SimpleUploadedFile
+
+ zip_file = SimpleUploadedFile("app.zip", VALID_ZIP, content_type="application/zip")
+ response = self.client.post(
+ self._url(app.short_id, "upload_version/"),
+ data={"file": zip_file},
+ format="multipart",
+ )
+ assert response.status_code == status.HTTP_201_CREATED
+ assert response.json()["version_number"] == 2
+ mock_storage_write.assert_called_once()
+
+ def test_upload_version_no_file_400(self):
+ app = self._create_app()
+ response = self.client.post(self._url(app.short_id, "upload_version/"))
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "No file" in response.json()["detail"]
+
+ def test_upload_invalid_zip_400(self):
+ app = self._create_app()
+
+ from django.core.files.uploadedfile import SimpleUploadedFile
+
+ bad_zip = SimpleUploadedFile("app.zip", b"not a zip", content_type="application/zip")
+ response = self.client.post(
+ self._url(app.short_id, "upload_version/"),
+ data={"file": bad_zip},
+ format="multipart",
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "Invalid zip" in response.json()["detail"]
+
+ def test_upload_zip_missing_app_py_400(self):
+ app = self._create_app()
+ zip_bytes = _make_zip({"readme.txt": "no app.py here"})
+
+ from django.core.files.uploadedfile import SimpleUploadedFile
+
+ zip_file = SimpleUploadedFile("app.zip", zip_bytes, content_type="application/zip")
+ response = self.client.post(
+ self._url(app.short_id, "upload_version/"),
+ data={"file": zip_file},
+ format="multipart",
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ @patch("posthog.storage.object_storage.write")
+ def test_upload_version_stops_live_sandbox(self, _mock_storage_write):
+ """Uploading a new version implicitly activates it, so any running
+ sandbox is now serving stale code and must be stopped."""
+ from django.core.files.uploadedfile import SimpleUploadedFile
+
+ app = self._create_app()
+ v1 = self._create_version(app, 1)
+ app.active_version = v1
+ app.save()
+ StreamlitAppSandbox.objects.create(
+ app=app, version=v1, sandbox_id="sb_old", status=StreamlitAppSandbox.Status.RUNNING
+ )
+
+ zip_file = SimpleUploadedFile("app.zip", VALID_ZIP, content_type="application/zip")
+ with patch("products.streamlit_apps.backend.facade.api.AppRuntimeService") as runtime_cls:
+ response = self.client.post(
+ self._url(app.short_id, "upload_version/"),
+ data={"file": zip_file},
+ format="multipart",
+ )
+
+ assert response.status_code == status.HTTP_201_CREATED
+ runtime_cls.return_value.stop_app.assert_called_once_with(app)
+
+ def test_activate_version_returns_new_active_version(self):
+ app = self._create_app()
+ v1 = self._create_version(app, 1)
+ v2 = self._create_version(app, 2)
+ app.active_version = v2
+ app.save()
+
+ response = self.client.post(
+ self._url(app.short_id, "activate_version/"),
+ data={"version_number": 1},
+ )
+ assert response.status_code == status.HTTP_200_OK
+ data = response.json()
+ assert data["active_version"]["version_number"] == 1
+ # The server now stops the sandbox itself, so callers no longer need a
+ # `requires_restart` hint.
+ assert "requires_restart" not in data
+ app.refresh_from_db()
+ assert app.active_version_id == v1.id
+
+ @parameterized.expand(
+ [
+ (StreamlitAppSandbox.Status.RUNNING, True),
+ (StreamlitAppSandbox.Status.STARTING, True),
+ (StreamlitAppSandbox.Status.STOPPED, False),
+ (StreamlitAppSandbox.Status.STOPPING, False),
+ (StreamlitAppSandbox.Status.ERROR, False),
+ ]
+ )
+ def test_activate_version_stops_live_sandbox(self, sandbox_status, should_stop):
+ app = self._create_app()
+ self._create_version(app, 1)
+ v2 = self._create_version(app, 2)
+ app.active_version = v2
+ app.save()
+ StreamlitAppSandbox.objects.create(app=app, version=v2, sandbox_id="sb_old", status=sandbox_status)
+
+ with patch("products.streamlit_apps.backend.facade.api.AppRuntimeService") as runtime_cls:
+ response = self.client.post(
+ self._url(app.short_id, "activate_version/"),
+ data={"version_number": 1},
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ if should_stop:
+ runtime_cls.return_value.stop_app.assert_called_once_with(app)
+ else:
+ runtime_cls.return_value.stop_app.assert_not_called()
+
+ def test_activate_version_swallows_stop_failure(self):
+ """Stop is best-effort: a Modal/runtime hiccup must not break activation."""
+ app = self._create_app()
+ v1 = self._create_version(app, 1)
+ v2 = self._create_version(app, 2)
+ app.active_version = v2
+ app.save()
+ StreamlitAppSandbox.objects.create(
+ app=app, version=v2, sandbox_id="sb_old", status=StreamlitAppSandbox.Status.RUNNING
+ )
+
+ with patch("products.streamlit_apps.backend.facade.api.AppRuntimeService") as runtime_cls:
+ runtime_cls.return_value.stop_app.side_effect = RuntimeError("Modal down")
+ response = self.client.post(
+ self._url(app.short_id, "activate_version/"),
+ data={"version_number": 1},
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ app.refresh_from_db()
+ assert app.active_version_id == v1.id
+
+ def test_activate_nonexistent_version_404(self):
+ app = self._create_app()
+ response = self.client.post(
+ self._url(app.short_id, "activate_version/"),
+ data={"version_number": 999},
+ )
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+
+ def test_activate_version_requires_version_number(self):
+ app = self._create_app()
+ response = self.client.post(self._url(app.short_id, "activate_version/"))
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ @parameterized.expand([("string", "abc"), ("float", 1.5), ("bool", True)])
+ def test_activate_version_rejects_non_integer(self, _name, version_number):
+ # A non-integer would otherwise hit the ORM and raise a 500 rather than a 400.
+ app = self._create_app()
+ self._create_version(app, 1)
+ response = self.client.post(
+ self._url(app.short_id, "activate_version/"),
+ data={"version_number": version_number},
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ @patch("posthog.storage.object_storage.write")
+ def test_upload_version_too_large_413(self, mock_storage_write):
+ from django.core.files.uploadedfile import SimpleUploadedFile
+
+ from products.streamlit_apps.backend.logic.zip_validator import MAX_ZIP_SIZE
+
+ app = self._create_app()
+ oversized = SimpleUploadedFile("app.zip", b"\0" * (MAX_ZIP_SIZE + 1), content_type="application/zip")
+ response = self.client.post(
+ self._url(app.short_id, "upload_version/"),
+ data={"file": oversized},
+ format="multipart",
+ )
+ assert response.status_code == status.HTTP_413_REQUEST_ENTITY_TOO_LARGE
+ # The body is rejected by size before it is ever read or persisted.
+ mock_storage_write.assert_not_called()
+
+
+class TestStreamlitAppSandboxControlAPI(_StreamlitAppsFlagMixin, APIBaseTest):
+ def _url(self, short_id: str, suffix: str = "") -> str:
+ base = f"/api/projects/{self.team.id}/streamlit_apps/{short_id}"
+ if suffix:
+ return f"{base}/{suffix}"
+ return f"{base}/"
+
+ def _create_app_with_version(self) -> StreamlitApp:
+ app = StreamlitApp.objects.create(team=self.team, name="Test App", created_by=self.user)
+ version = StreamlitAppVersion.objects.create(
+ app=app, version_number=1, zip_file="test.zip", zip_hash="abc", created_by=self.user
+ )
+ app.active_version = version
+ app.save()
+ return app
+
+ def test_status_no_sandbox(self):
+ app = self._create_app_with_version()
+ response = self.client.get(self._url(app.short_id, "status/"))
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["status"] == "stopped"
+
+ def test_status_with_sandbox(self):
+ app = self._create_app_with_version()
+ StreamlitAppSandbox.objects.create(
+ app=app,
+ version=app.active_version,
+ sandbox_id="sb_123",
+ status="running",
+ )
+ response = self.client.get(self._url(app.short_id, "status/"))
+ assert response.status_code == status.HTTP_200_OK
+ data = response.json()
+ assert data["status"] == "running"
+
+ @patch("products.streamlit_apps.backend.tasks.run_streamlit_app_lifecycle.delay")
+ def test_start_app_dispatches_task(self, mock_delay):
+ app = self._create_app_with_version()
+
+ response = self.client.post(self._url(app.short_id, "start/"))
+ assert response.status_code == status.HTTP_202_ACCEPTED
+ mock_delay.assert_called_once_with(str(app.id), "start", team_id=app.team_id)
+
+ def test_start_app_no_version_400(self):
+ app = StreamlitApp.objects.create(team=self.team, name="No Version", created_by=self.user)
+ response = self.client.post(self._url(app.short_id, "start/"))
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "No active version" in response.json()["detail"]
+
+ @patch("products.streamlit_apps.backend.facade.api.AppRuntimeService")
+ def test_stop_app(self, mock_runtime_cls):
+ mock_runtime = MagicMock()
+ mock_runtime_cls.return_value = mock_runtime
+ app = self._create_app_with_version()
+
+ response = self.client.post(self._url(app.short_id, "stop/"))
+ assert response.status_code == status.HTTP_200_OK
+ mock_runtime.stop_app.assert_called_once_with(app)
+
+ @patch("products.streamlit_apps.backend.tasks.run_streamlit_app_lifecycle.delay")
+ def test_restart_app_dispatches_task(self, mock_delay):
+ app = self._create_app_with_version()
+
+ response = self.client.post(self._url(app.short_id, "restart/"))
+ assert response.status_code == status.HTTP_202_ACCEPTED
+ mock_delay.assert_called_once_with(str(app.id), "restart", team_id=app.team_id)
+
+ @patch("products.streamlit_apps.backend.facade.api.AppRuntimeService")
+ def test_connect_info_returns_iframe_url_with_tokens(self, mock_runtime_cls):
+ mock_runtime = MagicMock()
+ mock_runtime.get_connect_url.return_value = {"url": "https://abc.modal.run", "token": "tok_123"}
+ mock_runtime_cls.return_value = mock_runtime
+
+ app = self._create_app_with_version()
+ StreamlitAppSandbox.objects.create(app=app, version=app.active_version, sandbox_id="sb_1", status="running")
+
+ response = self.client.get(self._url(app.short_id, "connect_info/"))
+ assert response.status_code == status.HTTP_200_OK
+ data = response.json()
+ assert "iframe_url" in data
+ assert "expires_in" in data
+ assert "https://abc.modal.run" in data["iframe_url"]
+ assert "_posthog_token=" in data["iframe_url"]
+ assert "_modal_connect_token=tok_123" in data["iframe_url"]
+ # expires_in is the REAL remaining lifetime of the minted iframe token
+ # (max 3600s for a freshly minted token, strictly less once clock drifts).
+ # Allow a small tolerance because the token is minted and then the expires
+ # datetime is recomputed a few ms later in the view.
+ assert 3590 <= data["expires_in"] <= 3600
+
+ @patch("products.streamlit_apps.backend.facade.api.AppRuntimeService")
+ def test_connect_info_omits_modal_token_when_none(self, mock_runtime_cls):
+ # Docker sandboxes have no Modal connect token (token=None). The iframe
+ # URL must not embed the literal string "None" as a token.
+ mock_runtime = MagicMock()
+ mock_runtime.get_connect_url.return_value = {"url": "http://localhost:49153", "token": None}
+ mock_runtime_cls.return_value = mock_runtime
+
+ app = self._create_app_with_version()
+ StreamlitAppSandbox.objects.create(app=app, version=app.active_version, sandbox_id="sb_1", status="running")
+
+ response = self.client.get(self._url(app.short_id, "connect_info/"))
+ assert response.status_code == status.HTTP_200_OK
+ iframe_url = response.json()["iframe_url"]
+ assert "None" not in iframe_url
+ assert "_modal_connect_token=None" not in iframe_url
+ assert "_posthog_token=" in iframe_url
+
+ def test_connect_info_not_running_returns_503(self):
+ app = self._create_app_with_version()
+ response = self.client.get(self._url(app.short_id, "connect_info/"))
+ assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE
+
+ @patch("products.streamlit_apps.backend.facade.api.AppRuntimeService")
+ def test_connect_info_updates_last_activity(self, mock_runtime_cls):
+ mock_runtime = MagicMock()
+ mock_runtime.get_connect_url.return_value = {"url": "https://x.modal.run", "token": "tok"}
+ mock_runtime_cls.return_value = mock_runtime
+
+ app = self._create_app_with_version()
+ sandbox_record = StreamlitAppSandbox.objects.create(
+ app=app, version=app.active_version, sandbox_id="sb_1", status="running"
+ )
+ assert sandbox_record.last_activity_at is None
+
+ self.client.get(self._url(app.short_id, "connect_info/"))
+ sandbox_record.refresh_from_db()
+ assert sandbox_record.last_activity_at is not None
+
+ @patch("products.streamlit_apps.backend.facade.api.AppRuntimeService")
+ def test_connect_info_debounces_last_activity_writes(self, mock_runtime_cls):
+ """connect_info is polled every ~2 seconds by the frontend token
+ refresher; writing last_activity_at on every call used to translate
+ to a per-sandbox row update every 2 seconds per active viewer. The
+ write is now debounced to once per _LAST_ACTIVITY_DEBOUNCE_SECONDS."""
+ from datetime import timedelta
+
+ mock_runtime = MagicMock()
+ mock_runtime.get_connect_url.return_value = {"url": "https://x.modal.run", "token": "tok"}
+ mock_runtime_cls.return_value = mock_runtime
+
+ app = self._create_app_with_version()
+ recent = timezone.now() - timedelta(seconds=5)
+ sandbox_record = StreamlitAppSandbox.objects.create(
+ app=app,
+ version=app.active_version,
+ sandbox_id="sb_1",
+ status="running",
+ last_activity_at=recent,
+ )
+
+ self.client.get(self._url(app.short_id, "connect_info/"))
+ sandbox_record.refresh_from_db()
+ # last_activity_at is still the old value — the second call was
+ # within the debounce window and skipped the UPDATE.
+ assert sandbox_record.last_activity_at == recent
+
+ # Rewind the last_activity_at past the debounce window and retry.
+ stale = timezone.now() - timedelta(seconds=120)
+ StreamlitAppSandbox.objects.filter(id=sandbox_record.id).update(last_activity_at=stale)
+ self.client.get(self._url(app.short_id, "connect_info/"))
+ sandbox_record.refresh_from_db()
+ assert sandbox_record.last_activity_at > stale
+
+ @patch("products.streamlit_apps.backend.facade.api.AppRuntimeService")
+ def test_connect_info_runtime_failure_returns_502(self, mock_runtime_cls):
+ mock_runtime = MagicMock()
+ mock_runtime.get_connect_url.return_value = None
+ mock_runtime_cls.return_value = mock_runtime
+
+ app = self._create_app_with_version()
+ StreamlitAppSandbox.objects.create(app=app, version=app.active_version, sandbox_id="sb_1", status="running")
+
+ response = self.client.get(self._url(app.short_id, "connect_info/"))
+ assert response.status_code == status.HTTP_502_BAD_GATEWAY
+
+ @patch("products.streamlit_apps.backend.facade.api.AppRuntimeService")
+ def test_connect_info_creates_oauth_token(self, mock_runtime_cls):
+ mock_runtime = MagicMock()
+ mock_runtime.get_connect_url.return_value = {"url": "https://abc.modal.run", "token": "tok"}
+ mock_runtime_cls.return_value = mock_runtime
+
+ app = self._create_app_with_version()
+ StreamlitAppSandbox.objects.create(app=app, version=app.active_version, sandbox_id="sb_1", status="running")
+
+ from posthog.models.oauth import OAuthAccessToken
+
+ initial_count = OAuthAccessToken.objects.filter(user=self.user).count()
+
+ self.client.get(self._url(app.short_id, "connect_info/"))
+
+ assert OAuthAccessToken.objects.filter(user=self.user).count() == initial_count + 1
+ token = OAuthAccessToken.objects.filter(user=self.user).order_by("-id").first()
+ assert token.scoped_teams == [self.team.id]
+ # Iframe-scoped — must NOT be a bridge token, so a stolen iframe URL
+ # can't be replayed against the streamlit bridge endpoint.
+ assert token.scope == "streamlit:iframe"
+
+ @patch("products.streamlit_apps.backend.facade.api.AppRuntimeService")
+ def test_connect_info_reuses_existing_token(self, mock_runtime_cls):
+ """A second connect_info call within the reuse window should reuse
+ the existing token rather than minting a fresh one — this is what
+ keeps the OAuth token table from growing on every iframe poll."""
+ mock_runtime = MagicMock()
+ mock_runtime.get_connect_url.return_value = {"url": "https://abc.modal.run", "token": "tok"}
+ mock_runtime_cls.return_value = mock_runtime
+
+ app = self._create_app_with_version()
+ StreamlitAppSandbox.objects.create(app=app, version=app.active_version, sandbox_id="sb_1", status="running")
+
+ from posthog.models.oauth import OAuthAccessToken
+
+ self.client.get(self._url(app.short_id, "connect_info/"))
+ first_count = OAuthAccessToken.objects.filter(user=self.user).count()
+
+ self.client.get(self._url(app.short_id, "connect_info/"))
+ second_count = OAuthAccessToken.objects.filter(user=self.user).count()
+
+ assert first_count == second_count, "expected token reuse, but a new token was minted"
diff --git a/products/streamlit_apps/frontend/generated/api.schemas.ts b/products/streamlit_apps/frontend/generated/api.schemas.ts
new file mode 100644
index 000000000000..f959e957867c
--- /dev/null
+++ b/products/streamlit_apps/frontend/generated/api.schemas.ts
@@ -0,0 +1,158 @@
+/**
+ * Auto-generated from the Django backend OpenAPI schema.
+ * To modify these types, update the Django serializers or views, then run:
+ * hogli build:openapi
+ * Questions or issues? #team-devex on Slack
+ *
+ * PostHog API - generated
+ * OpenAPI spec version: 1.0.0
+ */
+/**
+ * @nullable
+ */
+export type StreamlitAppUserInfoApiHedgehogConfig = { [key: string]: unknown } | null
+
+export interface StreamlitAppUserInfoApi {
+ id: number
+ uuid: string
+ /** @nullable */
+ distinct_id: string | null
+ first_name: string
+ last_name: string
+ email: string
+ /** @nullable */
+ is_email_verified: boolean | null
+ /** @nullable */
+ hedgehog_config: StreamlitAppUserInfoApiHedgehogConfig
+ /** @nullable */
+ role_at_organization: string | null
+}
+
+export interface AppContractApi {
+ /** User who created this app. */
+ created_by?: StreamlitAppUserInfoApi | null
+ id: string
+ short_id: string
+ name: string
+ description: string
+ cpu_cores: number
+ memory_gb: number
+ status: string
+ created_at: string
+ updated_at: string
+}
+
+export interface PaginatedAppContractListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: AppContractApi[]
+}
+
+export interface CreateAppInputApi {
+ /** Name of the app. */
+ name: string
+ /** Optional description of the app. */
+ description?: string
+ /** CPU cores allocated to the sandbox. */
+ cpu_cores?: number
+ /** Memory in GB allocated to the sandbox. */
+ memory_gb?: number
+}
+
+export interface UpdateAppInputApi {
+ /** New name for the app. */
+ name?: string
+ /** New description for the app. */
+ description?: string
+ /** New CPU core allocation for the sandbox. */
+ cpu_cores?: number
+ /** New memory (GB) allocation for the sandbox. */
+ memory_gb?: number
+}
+
+export interface PatchedUpdateAppInputApi {
+ /** New name for the app. */
+ name?: string
+ /** New description for the app. */
+ description?: string
+ /** New CPU core allocation for the sandbox. */
+ cpu_cores?: number
+ /** New memory (GB) allocation for the sandbox. */
+ memory_gb?: number
+}
+
+export interface ActivateVersionRequestApi {
+ /** Version number to activate. Must reference an existing version of this app. */
+ version_number: number
+}
+
+export interface AppVersionContractApi {
+ /** User who uploaded this version. */
+ created_by?: StreamlitAppUserInfoApi | null
+ id: string
+ version_number: number
+ zip_hash: string
+ /** @nullable */
+ snapshot_id: string | null
+ created_at: string
+}
+
+export interface ActivateVersionResponseApi {
+ /** The version that is now active for the app. */
+ active_version: AppVersionContractApi
+}
+
+export interface StreamlitConnectInfoApi {
+ /** Authenticated URL to embed the running app in an iframe. */
+ iframe_url: string
+ /** Seconds until the embedded session credential expires. */
+ expires_in: number
+}
+
+export interface StreamlitAppStatusApi {
+ /** Sandbox lifecycle status, or 'stopped' when no sandbox exists. */
+ status: string
+ /** Number of times the app's sandbox has been restarted. */
+ restart_count: number
+ /** Most recent sandbox error message, empty when there is none. */
+ last_error: string
+ /**
+ * When the current sandbox started, null when stopped.
+ * @nullable
+ */
+ started_at: string | null
+ /**
+ * Timestamp of the last recorded viewer activity, null when none.
+ * @nullable
+ */
+ last_activity_at: string | null
+ /**
+ * Version number the running sandbox was booted from.
+ * @nullable
+ */
+ version_number?: number | null
+}
+
+export interface UploadVersionRequestApi {
+ /** Zip archive containing the Streamlit app sources (max 10 MB). */
+ file: string
+}
+
+export interface StreamlitAppVersionListApi {
+ /** Most recent versions of the app, newest first (capped at 50). */
+ results: AppVersionContractApi[]
+}
+
+export type StreamlitAppsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+}
diff --git a/products/streamlit_apps/frontend/generated/api.ts b/products/streamlit_apps/frontend/generated/api.ts
new file mode 100644
index 000000000000..5521e31cbbb9
--- /dev/null
+++ b/products/streamlit_apps/frontend/generated/api.ts
@@ -0,0 +1,303 @@
+import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
+/**
+ * Auto-generated from the Django backend OpenAPI schema.
+ * To modify these types, update the Django serializers or views, then run:
+ * hogli build:openapi
+ * Questions or issues? #team-devex on Slack
+ *
+ * PostHog API - generated
+ * OpenAPI spec version: 1.0.0
+ */
+import type {
+ ActivateVersionRequestApi,
+ ActivateVersionResponseApi,
+ AppContractApi,
+ AppVersionContractApi,
+ CreateAppInputApi,
+ PaginatedAppContractListApi,
+ PatchedUpdateAppInputApi,
+ StreamlitAppStatusApi,
+ StreamlitAppVersionListApi,
+ StreamlitAppsListParams,
+ StreamlitConnectInfoApi,
+ UpdateAppInputApi,
+ UploadVersionRequestApi,
+} from './api.schemas'
+
+export const getStreamlitAppsListUrl = (projectId: string, params?: StreamlitAppsListParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/streamlit_apps/?${stringifiedParams}`
+ : `/api/projects/${projectId}/streamlit_apps/`
+}
+
+/**
+ * @summary List streamlit apps
+ */
+export const streamlitAppsList = async (
+ projectId: string,
+ params?: StreamlitAppsListParams,
+ options?: RequestInit
+): Promise<PaginatedAppContractListApi> => {
+ return apiMutator<PaginatedAppContractListApi>(getStreamlitAppsListUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getStreamlitAppsCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/streamlit_apps/`
+}
+
+/**
+ * @summary Create a streamlit app
+ */
+export const streamlitAppsCreate = async (
+ projectId: string,
+ createAppInputApi: CreateAppInputApi,
+ options?: RequestInit
+): Promise<AppContractApi> => {
+ return apiMutator<AppContractApi>(getStreamlitAppsCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(createAppInputApi),
+ })
+}
+
+export const getStreamlitAppsRetrieveUrl = (projectId: string, shortId: string) => {
+ return `/api/projects/${projectId}/streamlit_apps/${shortId}/`
+}
+
+/**
+ * @summary Retrieve a streamlit app
+ */
+export const streamlitAppsRetrieve = async (
+ projectId: string,
+ shortId: string,
+ options?: RequestInit
+): Promise<AppContractApi> => {
+ return apiMutator<AppContractApi>(getStreamlitAppsRetrieveUrl(projectId, shortId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getStreamlitAppsUpdateUrl = (projectId: string, shortId: string) => {
+ return `/api/projects/${projectId}/streamlit_apps/${shortId}/`
+}
+
+/**
+ * @summary Update a streamlit app
+ */
+export const streamlitAppsUpdate = async (
+ projectId: string,
+ shortId: string,
+ updateAppInputApi?: UpdateAppInputApi,
+ options?: RequestInit
+): Promise<AppContractApi> => {
+ return apiMutator<AppContractApi>(getStreamlitAppsUpdateUrl(projectId, shortId), {
+ ...options,
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(updateAppInputApi),
+ })
+}
+
+export const getStreamlitAppsPartialUpdateUrl = (projectId: string, shortId: string) => {
+ return `/api/projects/${projectId}/streamlit_apps/${shortId}/`
+}
+
+/**
+ * @summary Partially update a streamlit app
+ */
+export const streamlitAppsPartialUpdate = async (
+ projectId: string,
+ shortId: string,
+ patchedUpdateAppInputApi?: PatchedUpdateAppInputApi,
+ options?: RequestInit
+): Promise<AppContractApi> => {
+ return apiMutator<AppContractApi>(getStreamlitAppsPartialUpdateUrl(projectId, shortId), {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(patchedUpdateAppInputApi),
+ })
+}
+
+export const getStreamlitAppsDestroyUrl = (projectId: string, shortId: string) => {
+ return `/api/projects/${projectId}/streamlit_apps/${shortId}/`
+}
+
+/**
+ * @summary Delete a streamlit app
+ */
+export const streamlitAppsDestroy = async (
+ projectId: string,
+ shortId: string,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getStreamlitAppsDestroyUrl(projectId, shortId), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
+export const getStreamlitAppsActivateVersionCreateUrl = (projectId: string, shortId: string) => {
+ return `/api/projects/${projectId}/streamlit_apps/${shortId}/activate_version/`
+}
+
+/**
+ * @summary Activate an existing app version
+ */
+export const streamlitAppsActivateVersionCreate = async (
+ projectId: string,
+ shortId: string,
+ activateVersionRequestApi: ActivateVersionRequestApi,
+ options?: RequestInit
+): Promise<ActivateVersionResponseApi> => {
+ return apiMutator<ActivateVersionResponseApi>(getStreamlitAppsActivateVersionCreateUrl(projectId, shortId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(activateVersionRequestApi),
+ })
+}
+
+export const getStreamlitAppsConnectInfoRetrieveUrl = (projectId: string, shortId: string) => {
+ return `/api/projects/${projectId}/streamlit_apps/${shortId}/connect_info/`
+}
+
+/**
+ * @summary Get iframe connection info for a running app
+ */
+export const streamlitAppsConnectInfoRetrieve = async (
+ projectId: string,
+ shortId: string,
+ options?: RequestInit
+): Promise<StreamlitConnectInfoApi> => {
+ return apiMutator<StreamlitConnectInfoApi>(getStreamlitAppsConnectInfoRetrieveUrl(projectId, shortId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getStreamlitAppsRestartCreateUrl = (projectId: string, shortId: string) => {
+ return `/api/projects/${projectId}/streamlit_apps/${shortId}/restart/`
+}
+
+/**
+ * @summary Restart the app sandbox
+ */
+export const streamlitAppsRestartCreate = async (
+ projectId: string,
+ shortId: string,
+ options?: RequestInit
+): Promise<AppContractApi> => {
+ return apiMutator<AppContractApi>(getStreamlitAppsRestartCreateUrl(projectId, shortId), {
+ ...options,
+ method: 'POST',
+ })
+}
+
+export const getStreamlitAppsStartCreateUrl = (projectId: string, shortId: string) => {
+ return `/api/projects/${projectId}/streamlit_apps/${shortId}/start/`
+}
+
+/**
+ * @summary Start the app sandbox
+ */
+export const streamlitAppsStartCreate = async (
+ projectId: string,
+ shortId: string,
+ options?: RequestInit
+): Promise<AppContractApi> => {
+ return apiMutator<AppContractApi>(getStreamlitAppsStartCreateUrl(projectId, shortId), {
+ ...options,
+ method: 'POST',
+ })
+}
+
+export const getStreamlitAppsStatusRetrieveUrl = (projectId: string, shortId: string) => {
+ return `/api/projects/${projectId}/streamlit_apps/${shortId}/status/`
+}
+
+/**
+ * @summary Get app sandbox status
+ */
+export const streamlitAppsStatusRetrieve = async (
+ projectId: string,
+ shortId: string,
+ options?: RequestInit
+): Promise<StreamlitAppStatusApi> => {
+ return apiMutator<StreamlitAppStatusApi>(getStreamlitAppsStatusRetrieveUrl(projectId, shortId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getStreamlitAppsStopCreateUrl = (projectId: string, shortId: string) => {
+ return `/api/projects/${projectId}/streamlit_apps/${shortId}/stop/`
+}
+
+/**
+ * @summary Stop the app sandbox
+ */
+export const streamlitAppsStopCreate = async (
+ projectId: string,
+ shortId: string,
+ options?: RequestInit
+): Promise<AppContractApi> => {
+ return apiMutator<AppContractApi>(getStreamlitAppsStopCreateUrl(projectId, shortId), {
+ ...options,
+ method: 'POST',
+ })
+}
+
+export const getStreamlitAppsUploadVersionCreateUrl = (projectId: string, shortId: string) => {
+ return `/api/projects/${projectId}/streamlit_apps/${shortId}/upload_version/`
+}
+
+/**
+ * @summary Upload a new app version
+ */
+export const streamlitAppsUploadVersionCreate = async (
+ projectId: string,
+ shortId: string,
+ uploadVersionRequestApi: UploadVersionRequestApi,
+ options?: RequestInit
+): Promise<AppVersionContractApi> => {
+ return apiMutator<AppVersionContractApi>(getStreamlitAppsUploadVersionCreateUrl(projectId, shortId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(uploadVersionRequestApi),
+ })
+}
+
+export const getStreamlitAppsVersionsRetrieveUrl = (projectId: string, shortId: string) => {
+ return `/api/projects/${projectId}/streamlit_apps/${shortId}/versions/`
+}
+
+/**
+ * @summary List app versions
+ */
+export const streamlitAppsVersionsRetrieve = async (
+ projectId: string,
+ shortId: string,
+ options?: RequestInit
+): Promise<StreamlitAppVersionListApi> => {
+ return apiMutator<StreamlitAppVersionListApi>(getStreamlitAppsVersionsRetrieveUrl(projectId, shortId), {
+ ...options,
+ method: 'GET',
+ })
+}
diff --git a/products/streamlit_apps/frontend/generated/api.zod.ts b/products/streamlit_apps/frontend/generated/api.zod.ts
new file mode 100644
index 000000000000..28726059face
--- /dev/null
+++ b/products/streamlit_apps/frontend/generated/api.zod.ts
@@ -0,0 +1,56 @@
+/**
+ * Auto-generated Zod validation schemas from the Django backend OpenAPI schema.
+ * To modify these schemas, update the Django serializers or views, then run:
+ * hogli build:openapi
+ * Questions or issues? #team-devex on Slack
+ *
+ * PostHog API - generated
+ * OpenAPI spec version: 1.0.0
+ */
+import * as zod from 'zod'
+
+/**
+ * @summary Create a streamlit app
+ */
+export const StreamlitAppsCreateBody = /* @__PURE__ */ zod.object({
+ name: zod.string().describe('Name of the app.'),
+ description: zod.string().optional().describe('Optional description of the app.'),
+ cpu_cores: zod.number().optional().describe('CPU cores allocated to the sandbox.'),
+ memory_gb: zod.number().optional().describe('Memory in GB allocated to the sandbox.'),
+})
+
+/**
+ * @summary Update a streamlit app
+ */
+export const StreamlitAppsUpdateBody = /* @__PURE__ */ zod.object({
+ name: zod.string().optional().describe('New name for the app.'),
+ description: zod.string().optional().describe('New description for the app.'),
+ cpu_cores: zod.number().optional().describe('New CPU core allocation for the sandbox.'),
+ memory_gb: zod.number().optional().describe('New memory (GB) allocation for the sandbox.'),
+})
+
+/**
+ * @summary Partially update a streamlit app
+ */
+export const StreamlitAppsPartialUpdateBody = /* @__PURE__ */ zod.object({
+ name: zod.string().optional().describe('New name for the app.'),
+ description: zod.string().optional().describe('New description for the app.'),
+ cpu_cores: zod.number().optional().describe('New CPU core allocation for the sandbox.'),
+ memory_gb: zod.number().optional().describe('New memory (GB) allocation for the sandbox.'),
+})
+
+/**
+ * @summary Activate an existing app version
+ */
+export const StreamlitAppsActivateVersionCreateBody = /* @__PURE__ */ zod.object({
+ version_number: zod
+ .number()
+ .describe('Version number to activate. Must reference an existing version of this app.'),
+})
+
+/**
+ * @summary Upload a new app version
+ */
+export const StreamlitAppsUploadVersionCreateBody = /* @__PURE__ */ zod.object({
+ file: zod.url().describe('Zip archive containing the Streamlit app sources (max 10 MB).'),
+})
diff --git a/products/streamlit_apps/turbo.json b/products/streamlit_apps/turbo.json
index 34a16b3d30ce..e16d4eabe6e9 100644
--- a/products/streamlit_apps/turbo.json
+++ b/products/streamlit_apps/turbo.json
@@ -2,7 +2,7 @@
"extends": ["//"],
"tasks": {
"backend:contract-check": {
- "inputs": ["backend/facade/**", "backend/presentation/**"],
+ "inputs": ["backend/facade/**", "backend/presentation/**", "backend/routes.py"],
"outputs": [],
"cache": true
}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 8ee4c2bdc673..8f3a86eff01f 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -1859,6 +1859,48 @@ export namespace Schemas {
hideAggregation?: boolean | null;
}
+ export interface ActivateVersionRequest {
+ /** Version number to activate. Must reference an existing version of this app. */
+ version_number: number;
+ }
+
+ /**
+ * @nullable
+ */
+ export type StreamlitAppUserInfoHedgehogConfig = { [key: string]: unknown } | null;
+
+ export interface StreamlitAppUserInfo {
+ id: number;
+ uuid: string;
+ /** @nullable */
+ distinct_id: string | null;
+ first_name: string;
+ last_name: string;
+ email: string;
+ /** @nullable */
+ is_email_verified: boolean | null;
+ /** @nullable */
+ hedgehog_config: StreamlitAppUserInfoHedgehogConfig;
+ /** @nullable */
+ role_at_organization: string | null;
+ }
+
+ export interface AppVersionContract {
+ /** User who uploaded this version. */
+ created_by?: StreamlitAppUserInfo | null;
+ id: string;
+ version_number: number;
+ zip_hash: string;
+ /** @nullable */
+ snapshot_id: string | null;
+ created_at: string;
+ }
+
+ export interface ActivateVersionResponse {
+ /** The version that is now active for the app. */
+ active_version: AppVersionContract;
+ }
+
/**
* Schema for a single active breakpoint
*/
@@ -9425,6 +9467,20 @@ export namespace Schemas {
hidden_in_user_interface?: boolean | null;
}
+ export interface AppContract {
+ /** User who created this app. */
+ created_by?: StreamlitAppUserInfo | null;
+ id: string;
+ short_id: string;
+ name: string;
+ description: string;
+ cpu_cores: number;
+ memory_gb: number;
+ status: string;
+ created_at: string;
+ updated_at: string;
+ }
+
export interface AppMetricSeries {
name: string;
values: number[];
@@ -14203,6 +14259,17 @@ export namespace Schemas {
GithubRepo: 'github_repo',
} as const;
+ export interface CreateAppInput {
+ /** Name of the app. */
+ name: string;
+ /** Optional description of the app. */
+ description?: string;
+ /** CPU cores allocated to the sandbox. */
+ cpu_cores?: number;
+ /** Memory in GB allocated to the sandbox. */
+ memory_gb?: number;
+ }
+
/**
* Typed configuration for a FileDownload batch-export destination.
*/
@@ -32822,6 +32889,15 @@ export namespace Schemas {
results: Annotation[];
}
+ export interface PaginatedAppContractList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: AppContract[];
+ }
+
export interface PaginatedApprovalPolicyList {
count: number;
/** @nullable */
@@ -44127,6 +44203,17 @@ export namespace Schemas {
readonly updated_at?: string | null;
}
+ export interface PatchedUpdateAppInput {
+ /** New name for the app. */
+ name?: string;
+ /** New description for the app. */
+ description?: string;
+ /** New CPU core allocation for the sandbox. */
+ cpu_cores?: number;
+ /** New memory (GB) allocation for the sandbox. */
+ memory_gb?: number;
+ }
+
export type SessionReplayListWidgetUpdateRequestOpenApiWidgetType = typeof SessionReplayListWidgetUpdateRequestOpenApiWidgetType[keyof typeof SessionReplayListWidgetUpdateRequestOpenApiWidgetType];
@@ -53703,6 +53790,42 @@ export namespace Schemas {
stream_base_url: string | null;
}
+ export interface StreamlitAppStatus {
+ /** Sandbox lifecycle status, or 'stopped' when no sandbox exists. */
+ status: string;
+ /** Number of times the app's sandbox has been restarted. */
+ restart_count: number;
+ /** Most recent sandbox error message, empty when there is none. */
+ last_error: string;
+ /**
+ * When the current sandbox started, null when stopped.
+ * @nullable
+ */
+ started_at: string | null;
+ /**
+ * Timestamp of the last recorded viewer activity, null when none.
+ * @nullable
+ */
+ last_activity_at: string | null;
+ /**
+ * Version number the running sandbox was booted from.
+ * @nullable
+ */
+ version_number?: number | null;
+ }
+
+ export interface StreamlitAppVersionList {
+ /** Most recent versions of the app, newest first (capped at 50). */
+ results: AppVersionContract[];
+ }
+
+ export interface StreamlitConnectInfo {
+ /** Authenticated URL to embed the running app in an iframe. */
+ iframe_url: string;
+ /** Seconds until the embedded session credential expires. */
+ expires_in: number;
+ }
+
export interface SummaryBullet {
text: string;
line_refs: string;
@@ -55722,6 +55845,17 @@ export namespace Schemas {
target_language?: string;
}
+ export interface UpdateAppInput {
+ /** New name for the app. */
+ name?: string;
+ /** New description for the app. */
+ description?: string;
+ /** New CPU core allocation for the sandbox. */
+ cpu_cores?: number;
+ /** New memory (GB) allocation for the sandbox. */
+ memory_gb?: number;
+ }
+
/**
* Body shape for PUT /revisions/<id>/bundle/file/.
*
@@ -55763,6 +55897,11 @@ export namespace Schemas {
color?: string | null;
}
+ export interface UploadVersionRequest {
+ /** Zip archive containing the Streamlit app sources (max 10 MB). */
+ file: string;
+ }
+
/**
* Optional structured plan of events the wizard intends to instrument. Schema is workflow-specific.
* @nullable
@@ -63609,6 +63748,7 @@ export namespace Schemas {
* * `InstanceSetting` - InstanceSetting
* * `SignalReport` - SignalReport
* * `SignalScoutConfig` - SignalScoutConfig
+ * * `StreamlitApp` - StreamlitApp
* @minLength 1
*/
scope?: ActivityLogListScope;
@@ -63692,6 +63832,7 @@ export namespace Schemas {
InstanceSetting: 'InstanceSetting',
SignalReport: 'SignalReport',
SignalScoutConfig: 'SignalScoutConfig',
+ StreamlitApp: 'StreamlitApp',
} as const;
/**
@@ -63761,6 +63902,7 @@ export namespace Schemas {
* * `InstanceSetting` - InstanceSetting
* * `SignalReport` - SignalReport
* * `SignalScoutConfig` - SignalScoutConfig
+ * * `StreamlitApp` - StreamlitApp
*/
export type ActivityLogListScopesItem = typeof ActivityLogListScopesItem[keyof typeof ActivityLogListScopesItem];
@@ -63832,6 +63974,7 @@ export namespace Schemas {
InstanceSetting: 'InstanceSetting',
SignalReport: 'SignalReport',
SignalScoutConfig: 'SignalScoutConfig',
+ StreamlitApp: 'StreamlitApp',
} as const;
export type AdvancedActivityLogsListParams = {
@@ -70086,6 +70229,17 @@ export namespace Schemas {
Unknown: 'unknown',
} as const;
+ export type StreamlitAppsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ };
+
export type SubscriptionsListParams = {
/**
* Filter by creator user UUID.
diff --git a/tach.toml b/tach.toml
index ae96625487dc..0393e873cbea 100644
--- a/tach.toml
+++ b/tach.toml
@@ -783,6 +783,16 @@ from = [
"products.user_interviews",
]
+# streamlit_apps exposes the HogQL bridge view, routed directly from posthog/urls.py.
+
+[[interfaces]]
+expose = [
+ "backend\\.presentation\\.bridge_views.*",
+]
+from = [
+ "products.streamlit_apps",
+]
+
# Legacy leaks — core (posthog/ee) imports these internals directly.
# Each block below should shrink as imports migrate to the facade.
# These products have had backend:contract-check removed from package.json