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 list, viewer, and edit frontend (#54880)

Jovan Sakovic2b8abae71966
diff --git a/frontend/package.json b/frontend/package.json
index 38a827659424..128523e1cb7f 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -128,6 +128,7 @@
"@posthog/products-session-summaries": "workspace:*",
"@posthog/products-skills": "workspace:*",
"@posthog/products-stamphog": "workspace:*",
+ "@posthog/products-streamlit-apps": "workspace:*",
"@posthog/products-subscriptions": "workspace:*",
"@posthog/products-surveys": "workspace:*",
"@posthog/products-tasks": "workspace:*",
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index f9c13cd17a8b..b941367bcf6f 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -487,6 +487,7 @@ export const FEATURE_FLAGS = {
SQL_EDITOR_QUERY_HISTORY: 'sql-editor-query-history', // owner: @annaszell #team-data-tools
SQL_EDITOR_VIM_MODE: 'sql-editor-vim-mode', // owner: @arthurdedeus
SSE_DASHBOARDS: 'sse-dashboards', // owner: @aspicer #team-analytics-platform
+ STREAMLIT_APPS: 'streamlit-apps', // owner: @sakce
SUBSCRIPTION_AI_PROMPT: 'ai-subscriptions', // owner: #team-analytics-platform, gates AI prompt-based subscriptions
SUBSCRIPTION_AI_SUMMARY_PROMPT_GUIDE: 'subscription-ai-summary-prompt-guide', // owner: #team-analytics-platform, gates the per-subscription prompt guide textarea
SUBSCRIPTION_TABBED_OVERVIEW: 'subscription-tabbed-overview', // owner: #team-analytics-platform, gates the tabbed subscriptions overview modal
diff --git a/frontend/src/productScenes.tsx b/frontend/src/productScenes.tsx
index 53c8ca22ee86..266f8b819c22 100644
--- a/frontend/src/productScenes.tsx
+++ b/frontend/src/productScenes.tsx
@@ -120,6 +120,9 @@ export const productScenes: Record<string, () => Promise<any>> = {
Skills: () => import('../../products/skills/frontend/LLMSkillsScene'),
Skill: () => import('../../products/skills/frontend/LLMSkillScene'),
Stamphog: () => import('../../products/stamphog/frontend/scenes/StamphogScene/StamphogScene'),
+ StreamlitApps: () => import('../../products/streamlit_apps/frontend/StreamlitApps'),
+ StreamlitApp: () => import('../../products/streamlit_apps/frontend/StreamlitApp'),
+ StreamlitAppEdit: () => import('../../products/streamlit_apps/frontend/StreamlitAppEdit'),
Subscriptions: () => import('../../products/subscriptions/frontend/scenes/SubscriptionsScene'),
Subscription: () => import('../../products/subscriptions/frontend/scenes/SubscriptionScene'),
SlackTaskContext: () => import('../../products/tasks/frontend/SlackTaskContextScene'),
diff --git a/frontend/src/products.json b/frontend/src/products.json
index 93d5573ff15b..613773f107ca 100644
--- a/frontend/src/products.json
+++ b/frontend/src/products.json
@@ -224,6 +224,13 @@
},
{ "path": "Code review", "category": "Unreleased", "iconType": null, "type": null, "intents": ["review_hog"] },
{ "path": "Skills", "category": "Tools", "iconType": null, "type": "llm_skills", "intents": ["skills"] },
+ {
+ "path": "Apps",
+ "category": "Unreleased",
+ "iconType": "tools",
+ "type": "streamlit_app",
+ "intents": ["streamlit_apps"]
+ },
{ "path": "Surveys", "category": "Behavior", "iconType": "survey", "type": "survey", "intents": ["surveys"] },
{ "path": "Toolbar", "category": "Tools", "iconType": "toolbar", "type": "toolbar", "intents": ["toolbar"] },
{
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsx
index da5b362bacda..8f51880602ad 100644
--- a/frontend/src/products.tsx
+++ b/frontend/src/products.tsx
@@ -200,6 +200,10 @@ export const productRoutes: Record<string, [string, string]> = {
'/skills/:name': ['Skill', 'skill'],
'/stamphog': ['Stamphog', 'stamphog'],
'/stamphog/install/callback': ['Stamphog', 'stamphogCallback'],
+ '/streamlit-apps': ['StreamlitApps', 'streamlitApps'],
+ '/streamlit-apps/new': ['StreamlitAppEdit', 'streamlitAppNew'],
+ '/streamlit-apps/:id': ['StreamlitApp', 'streamlitApp'],
+ '/streamlit-apps/:id/edit': ['StreamlitAppEdit', 'streamlitAppEdit'],
'/subscriptions': ['Subscriptions', 'subscriptions'],
'/subscriptions/new': ['Subscriptions', 'subscriptionNew'],
'/subscriptions/:subscriptionId/edit': ['Subscriptions', 'subscriptionEdit'],
@@ -796,6 +800,9 @@ export const productConfiguration: Record<string, any> = {
},
Skill: { projectBased: true, name: 'Skill', layout: 'app-container', iconType: 'llm_prompts' },
Stamphog: { projectBased: true, name: 'Stamphog', iconType: 'stamphog' },
+ StreamlitApps: { name: 'Streamlit apps', projectBased: true },
+ StreamlitApp: { name: 'Streamlit app', projectBased: true },
+ StreamlitAppEdit: { name: 'Edit Streamlit app', projectBased: true },
Subscriptions: {
projectBased: true,
name: 'Subscriptions',
@@ -1311,6 +1318,10 @@ export const productUrls = {
): string => combineUrl(`/skills/${name}`, params).url,
stamphog: (): string => '/stamphog',
stamphogCallback: (): string => '/stamphog/install/callback',
+ streamlitApps: (): string => '/streamlit-apps',
+ streamlitApp: (id: string): string => `/streamlit-apps/${id}`,
+ streamlitAppEdit: (id: string): string => `/streamlit-apps/${id}/edit`,
+ streamlitAppNew: (): string => '/streamlit-apps/new',
subscriptions: (): string => '/subscriptions',
subscription: (id: string | number): string => `/subscriptions/${id}`,
subscriptionNew: (): string => '/subscriptions/new',
@@ -1682,6 +1693,18 @@ export const getTreeItemsProducts = (): FileSystemImport[] => [
sceneKey: 'AIGateway',
sceneKeys: ['AIGateway'],
},
+ {
+ path: 'Apps',
+ intents: [ProductKey.STREAMLIT_APPS],
+ href: urls.streamlitApps(),
+ type: 'streamlit_app',
+ category: ProductItemCategory.UNRELEASED,
+ flag: FEATURE_FLAGS.STREAMLIT_APPS,
+ iconType: 'tools',
+ iconColor: ['var(--color-product-data-pipeline-light)'] as FileSystemIconColor,
+ sceneKey: 'StreamlitApps',
+ sceneKeys: ['StreamlitApps', 'StreamlitApp', 'StreamlitAppEdit'],
+ },
{
path: 'Business knowledge',
intents: [ProductKey.CONVERSATIONS],
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 73fd12c8998c..0c23298b0b24 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -776,6 +776,9 @@ importers:
'@posthog/products-stamphog':
specifier: workspace:*
version: link:../products/stamphog
+ '@posthog/products-streamlit-apps':
+ specifier: workspace:*
+ version: link:../products/streamlit_apps
'@posthog/products-subscriptions':
specifier: workspace:*
version: link:../products/subscriptions
@@ -4342,7 +4345,29 @@ importers:
specifier: 'catalog:'
version: 0.2.4([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))
- products/streamlit_apps: {}
+ products/streamlit_apps:
+ dependencies:
+ '@posthog/icons':
+ specifier: '*'
+ '@posthog/lemon-ui':
+ specifier: '*'
+ '@types/react':
+ specifier: 18.3.27
+ version: 18.3.27
+ kea:
+ specifier: 'catalog:'
+ version: 4.0.0-pre.6([email protected])
+ kea-loaders:
+ specifier: 'catalog:'
+ kea-router:
+ specifier: 'catalog:'
+ react:
+ specifier: 18.3.1
+ version: 18.3.1
products/subscriptions:
dependencies:
diff --git a/products/streamlit_apps/backend/presentation/serializers.py b/products/streamlit_apps/backend/presentation/serializers.py
index f737583313ca..7f7325f9868e 100644
--- a/products/streamlit_apps/backend/presentation/serializers.py
+++ b/products/streamlit_apps/backend/presentation/serializers.py
@@ -1,6 +1,7 @@
from typing import TYPE_CHECKING, cast
import posthoganalytics
+from drf_spectacular.utils import extend_schema_serializer
from rest_framework import serializers
from rest_framework.permissions import BasePermission
from rest_framework.request import Request
@@ -42,6 +43,9 @@ class StreamlitAppSandboxSerializer(DataclassSerializer):
dataclass = AppSandboxContract
+# Shares AppContract with StreamlitAppSerializer, so without its own component name the two
+# collapse into one schema and the fuller one loses active_version/sandbox.
+@extend_schema_serializer(component_name="AppSummaryContract")
class StreamlitAppMinimalSerializer(DataclassSerializer):
created_by = StreamlitAppUserSerializer(allow_null=True, required=False, help_text="User who created this app.")
diff --git a/products/streamlit_apps/frontend/StreamlitApp.tsx b/products/streamlit_apps/frontend/StreamlitApp.tsx
new file mode 100644
index 000000000000..5e14b64c4b14
--- /dev/null
+++ b/products/streamlit_apps/frontend/StreamlitApp.tsx
@@ -0,0 +1,182 @@
+import { useActions, useValues } from 'kea'
+
+import { IconPencil } from '@posthog/icons'
+import { LemonBanner, LemonButton } from '@posthog/lemon-ui'
+
+import { NotFound } from 'lib/components/NotFound'
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
+import { Spinner } from 'lib/lemon-ui/Spinner/Spinner'
+import { SceneExport } from 'scenes/sceneTypes'
+import { urls } from 'scenes/urls'
+
+import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
+
+import { StreamlitAppLoading } from './StreamlitAppLoading'
+import { StreamlitAppLogicProps, streamlitAppLogic } from './streamlitAppLogic'
+
+export const scene: SceneExport = {
+ component: StreamlitAppViewer,
+ logic: streamlitAppLogic,
+ paramsToProps: ({ params: { id } }): StreamlitAppLogicProps => ({
+ shortId: id as string,
+ }),
+}
+
+const GENERIC_ERROR_MESSAGE = 'Something went wrong starting your app. Check the logs or contact support.'
+
+// Keeps raw stack traces and DB errors out of the viewer UI.
+const ERROR_PREFIX_MESSAGES: Array<[string, string]> = [
+ [
+ 'Max restart count',
+ "We've hit the restart limit for this app. Try editing the source and uploading a new version.",
+ ],
+ ['Auth proxy failed to become ready', "The app's auth proxy didn't start in time. Try restarting."],
+ ['Startup timed out', 'Startup timed out. Try restarting.'],
+ ['Sandbox terminated', 'The sandbox stopped unexpectedly. Restart to try again.'],
+ ['No active version', 'No version uploaded yet. Upload a zip file from the edit page.'],
+]
+
+function curateErrorMessage(raw?: string | null): string {
+ if (!raw) {
+ return GENERIC_ERROR_MESSAGE
+ }
+ for (const [prefix, friendly] of ERROR_PREFIX_MESSAGES) {
+ if (raw.startsWith(prefix)) {
+ return friendly
+ }
+ }
+ return GENERIC_ERROR_MESSAGE
+}
+
+export function StreamlitAppViewer(props: Record<string, any>): JSX.Element {
+ const streamlitAppsFeatureFlagEnabled = useFeatureFlag('STREAMLIT_APPS')
+ const shortId = props.id as string
+ const { streamlitApp, streamlitAppLoading, appStatus, iframeSrc, sandboxStatus, connectError } = useValues(
+ streamlitAppLogic({ shortId })
+ )
+ const { startApp, restartApp, loadConnectInfo } = useActions(streamlitAppLogic({ shortId }))
+
+ if (!streamlitAppsFeatureFlagEnabled) {
+ return <NotFound object="page" />
+ }
+
+ if (streamlitAppLoading && !streamlitApp) {
+ return (
+ <div className="flex items-center justify-center py-20">
+ <Spinner className="text-4xl" />
+ </div>
+ )
+ }
+
+ if (!streamlitApp) {
+ return (
+ <div className="flex flex-col items-center justify-center py-20 text-center">
+ <h2 className="text-lg font-semibold mb-2">App not found</h2>
+ <p className="text-muted mb-4">This Streamlit app doesn't exist or you don't have access to it.</p>
+ <LemonButton type="primary" to={urls.streamlitApps()}>
+ Back to apps
+ </LemonButton>
+ </div>
+ )
+ }
+
+ return (
+ <div className="flex flex-col h-full">
+ <SceneTitleSection
+ name={streamlitApp.name}
+ resourceType={{ type: 'streamlit_app' }}
+ actions={
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconPencil />}
+ to={urls.streamlitAppEdit(streamlitApp.short_id)}
+ >
+ Edit
+ </LemonButton>
+ }
+ />
+ {/* Nudge on version mismatch between activated and running versions. */}
+ {appStatus === 'running' &&
+ streamlitApp.active_version &&
+ sandboxStatus?.version_number != null &&
+ streamlitApp.active_version.version_number !== sandboxStatus.version_number && (
+ <LemonBanner
+ type="info"
+ className="mb-2"
+ action={{
+ children: 'Restart now',
+ onClick: () => restartApp(),
+ }}
+ >
+ New version available — restart to apply the changes.
+ </LemonBanner>
+ )}
+ <div className="flex-1 min-h-0">
+ {appStatus === 'starting' && <StreamlitAppLoading />}
+
+ {appStatus === 'stopping' && <StreamlitAppLoading message="Stopping the app..." />}
+
+ {appStatus === 'running' && iframeSrc && (
+ <iframe
+ src={iframeSrc}
+ // allow-same-origin lets Streamlit read its own cookies/sessionStorage.
+ // PostHog is a different origin, so the proxy's scope check is the real boundary.
+ sandbox="allow-scripts allow-forms allow-popups allow-modals allow-same-origin"
+ referrerPolicy="no-referrer"
+ className="w-full h-full border-0 rounded-lg"
+ style={{ minHeight: '600px' }}
+ title={streamlitApp.name}
+ />
+ )}
+
+ {appStatus === 'running' && !iframeSrc && connectError && (
+ <div className="flex flex-col items-center justify-center py-20 text-center">
+ <h2 className="text-lg font-semibold mb-2">Connection failed</h2>
+ <p className="text-muted mb-6">{connectError}</p>
+ <LemonButton type="primary" onClick={() => loadConnectInfo()}>
+ Retry
+ </LemonButton>
+ </div>
+ )}
+
+ {appStatus === 'running' && !iframeSrc && !connectError && <StreamlitAppLoading />}
+
+ {appStatus === 'error' && (
+ <div className="flex flex-col items-center justify-center py-20 text-center">
+ <h2 className="text-lg font-semibold mb-2">App failed to start</h2>
+ <p className="text-muted mb-4 max-w-lg">{curateErrorMessage(sandboxStatus?.last_error)}</p>
+ <div className="flex gap-2">
+ <LemonButton type="primary" onClick={restartApp}>
+ Try again
+ </LemonButton>
+ <LemonButton type="secondary" to={urls.streamlitAppEdit(streamlitApp.short_id)}>
+ View settings
+ </LemonButton>
+ </div>
+ </div>
+ )}
+
+ {appStatus === 'stopped' && !streamlitApp.active_version && (
+ <div className="flex flex-col items-center justify-center py-20 text-center">
+ <h2 className="text-lg font-semibold mb-2">No version uploaded</h2>
+ <p className="text-muted mb-4">Upload a zip file to get started.</p>
+ <LemonButton type="primary" to={urls.streamlitAppEdit(streamlitApp.short_id)}>
+ Upload
+ </LemonButton>
+ </div>
+ )}
+
+ {appStatus === 'stopped' && streamlitApp.active_version && (
+ <div className="flex flex-col items-center justify-center py-20 text-center">
+ <h2 className="text-lg font-semibold mb-2">App is stopped</h2>
+ <p className="text-muted mb-4">Start the app to view it.</p>
+ <LemonButton type="primary" onClick={startApp}>
+ Start app
+ </LemonButton>
+ </div>
+ )}
+ </div>
+ </div>
+ )
+}
diff --git a/products/streamlit_apps/frontend/StreamlitAppEdit.tsx b/products/streamlit_apps/frontend/StreamlitAppEdit.tsx
new file mode 100644
index 000000000000..684db6134e76
--- /dev/null
+++ b/products/streamlit_apps/frontend/StreamlitAppEdit.tsx
@@ -0,0 +1,188 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton, LemonInput, LemonSelect, LemonTextArea } from '@posthog/lemon-ui'
+
+import { NotFound } from 'lib/components/NotFound'
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
+import { LemonLabel } from 'lib/lemon-ui/LemonLabel/LemonLabel'
+import { Spinner } from 'lib/lemon-ui/Spinner/Spinner'
+import { humanFriendlyDetailedTime } from 'lib/utils/datetime'
+import { SceneExport } from 'scenes/sceneTypes'
+import { urls } from 'scenes/urls'
+
+import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
+
+import { StreamlitAppEditLogicProps, streamlitAppEditLogic } from './streamlitAppEditLogic'
+import { StreamlitAppZipUpload } from './StreamlitAppZipUpload'
+
+export const scene: SceneExport = {
+ component: StreamlitAppEdit,
+ logic: streamlitAppEditLogic,
+ paramsToProps: ({ params: { id } }: { params: { id?: string } }): StreamlitAppEditLogicProps => ({
+ shortId: id || 'new',
+ }),
+}
+
+const CPU_OPTIONS = [
+ { value: 0.25, label: '0.25 cores' },
+ { value: 0.5, label: '0.5 cores' },
+ { value: 1, label: '1 core' },
+ { value: 2, label: '2 cores' },
+ { value: 4, label: '4 cores' },
+ { value: 8, label: '8 cores' },
+]
+
+const MEMORY_OPTIONS = [
+ { value: 0.5, label: '0.5 GB' },
+ { value: 1, label: '1 GB' },
+ { value: 2, label: '2 GB' },
+ { value: 4, label: '4 GB' },
+ { value: 8, label: '8 GB' },
+ { value: 16, label: '16 GB' },
+]
+
+export function StreamlitAppEdit(props: Record<string, any>): JSX.Element {
+ const streamlitAppsFeatureFlagEnabled = useFeatureFlag('STREAMLIT_APPS')
+ const shortId = (props.id as string) || 'new'
+ const {
+ streamlitApp,
+ streamlitAppLoading,
+ name,
+ description,
+ cpuCores,
+ memoryGb,
+ zipFile,
+ versions,
+ savedAppLoading,
+ } = useValues(streamlitAppEditLogic({ shortId }))
+ const {
+ setName,
+ setDescription,
+ setCpuCores,
+ setMemoryGb,
+ setZipFile,
+ setActiveVersionNumber,
+ saveApp,
+ deleteApp,
+ } = useActions(streamlitAppEditLogic({ shortId }))
+
+ if (!streamlitAppsFeatureFlagEnabled) {
+ return <NotFound object="page" />
+ }
+
+ const isNew = shortId === 'new'
+
+ if (!isNew && streamlitAppLoading) {
+ return (
+ <div className="flex items-center justify-center py-20">
+ <Spinner className="text-4xl" />
+ </div>
+ )
+ }
+
+ const canSave = name.trim().length > 0 && (isNew ? !!zipFile : true)
+
+ return (
+ <div>
+ <SceneTitleSection
+ name={isNew ? 'New app' : (streamlitApp?.name ?? 'Edit app')}
+ resourceType={{ type: 'streamlit_app' }}
+ />
+ <div className="max-w-xl space-y-6">
+ <div className="space-y-2">
+ <LemonLabel htmlFor="streamlit-app-name">Name</LemonLabel>
+ <LemonInput id="streamlit-app-name" value={name} onChange={setName} placeholder="My app" />
+ </div>
+
+ <div className="space-y-2">
+ <LemonLabel htmlFor="streamlit-app-description">Description</LemonLabel>
+ <LemonTextArea
+ id="streamlit-app-description"
+ value={description}
+ onChange={setDescription}
+ placeholder="What does this app do?"
+ />
+ </div>
+
+ <div className="space-y-2">
+ <LemonLabel>{isNew ? 'Upload' : 'Upload new version'}</LemonLabel>
+ <StreamlitAppZipUpload file={zipFile} onFileChange={setZipFile} />
+ </div>
+
+ {!isNew && versions.length > 0 && (
+ <div className="space-y-2">
+ <LemonLabel>Active version</LemonLabel>
+ <LemonSelect
+ value={streamlitApp?.active_version?.version_number}
+ onChange={(value) => {
+ if (value !== null && value !== undefined) {
+ setActiveVersionNumber(value)
+ }
+ }}
+ options={versions.map((v: { version_number: number; created_at: string }) => ({
+ value: v.version_number,
+ label: `v${v.version_number} — ${humanFriendlyDetailedTime(v.created_at)}`,
+ }))}
+ />
+ </div>
+ )}
+
+ <div className="space-y-2">
+ <LemonLabel>Resources</LemonLabel>
+ <div className="flex gap-4">
+ <div className="flex-1 space-y-1">
+ <span className="text-sm text-muted">CPU</span>
+ <LemonSelect value={cpuCores} onChange={setCpuCores} options={CPU_OPTIONS} fullWidth />
+ </div>
+ <div className="flex-1 space-y-1">
+ <span className="text-sm text-muted">Memory</span>
+ <LemonSelect value={memoryGb} onChange={setMemoryGb} options={MEMORY_OPTIONS} fullWidth />
+ </div>
+ </div>
+ </div>
+
+ <div className="flex justify-between pt-4">
+ {!isNew ? (
+ <LemonButton
+ type="secondary"
+ status="danger"
+ onClick={() => {
+ LemonDialog.open({
+ title: 'Delete app?',
+ description:
+ 'This will permanently delete this app and all its versions. This cannot be undone.',
+ primaryButton: {
+ children: 'Delete',
+ status: 'danger',
+ onClick: () => deleteApp(),
+ },
+ secondaryButton: {
+ children: 'Cancel',
+ },
+ })
+ }}
+ >
+ Delete
+ </LemonButton>
+ ) : (
+ <div />
+ )}
+ <div className="flex gap-2">
+ <LemonButton type="secondary" to={urls.streamlitApps()}>
+ Cancel
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ onClick={saveApp}
+ loading={savedAppLoading}
+ disabledReason={!canSave ? 'Fill in all required fields' : undefined}
+ >
+ {isNew ? 'Create app' : 'Save changes'}
+ </LemonButton>
+ </div>
+ </div>
+ </div>
+ </div>
+ )
+}
diff --git a/products/streamlit_apps/frontend/StreamlitAppLoading.tsx b/products/streamlit_apps/frontend/StreamlitAppLoading.tsx
new file mode 100644
index 000000000000..2fd128a36331
--- /dev/null
+++ b/products/streamlit_apps/frontend/StreamlitAppLoading.tsx
@@ -0,0 +1,17 @@
+import { Spinner } from 'lib/lemon-ui/Spinner/Spinner'
+
+interface StreamlitAppLoadingProps {
+ message?: string
+}
+
+export function StreamlitAppLoading({ message }: StreamlitAppLoadingProps = {}): JSX.Element {
+ return (
+ <div className="flex flex-col items-center justify-center py-20 text-center">
+ <h2 className="text-lg font-semibold mb-2">{message ?? 'Waking up the hedgehogs...'}</h2>
+ {!message && (
+ <p className="text-muted mb-6">Your app is starting. This usually takes about 10-30 seconds.</p>
+ )}
+ <Spinner className="text-4xl" />
+ </div>
+ )
+}
diff --git a/products/streamlit_apps/frontend/StreamlitAppZipUpload.tsx b/products/streamlit_apps/frontend/StreamlitAppZipUpload.tsx
new file mode 100644
index 000000000000..0f771d470c0c
--- /dev/null
+++ b/products/streamlit_apps/frontend/StreamlitAppZipUpload.tsx
@@ -0,0 +1,54 @@
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { LemonFileInput } from 'lib/lemon-ui/LemonFileInput/LemonFileInput'
+
+function humanFileSize(bytes: number): string {
+ if (bytes < 1024) {
+ return `${bytes} B`
+ }
+ if (bytes < 1024 * 1024) {
+ return `${(bytes / 1024).toFixed(1)} KB`
+ }
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
+}
+
+export function StreamlitAppZipUpload({
+ file,
+ onFileChange,
+}: {
+ file: File | null
+ onFileChange: (file: File | null) => void
+}): JSX.Element {
+ if (!file) {
+ return (
+ <LemonFileInput
+ accept=".zip"
+ multiple={false}
+ onChange={(files) => {
+ if (files.length > 0) {
+ onFileChange(files[0])
+ }
+ }}
+ showUploadedFiles={false}
+ callToAction="Drag and drop your zip file here, or click to browse"
+ />
+ )
+ }
+
+ return (
+ <div className="border rounded-lg p-4">
+ <div className="flex items-center justify-between">
+ <div>
+ <span className="font-medium">{file.name}</span>
+ <span className="text-muted ml-2">({humanFileSize(file.size)})</span>
+ </div>
+ <LemonButton size="small" type="secondary" onClick={() => onFileChange(null)}>
+ Remove
+ </LemonButton>
+ </div>
+ <p className="text-xs text-muted mt-2 mb-0">
+ Must contain app.py. Packages in requirements.txt will be validated on upload.
+ </p>
+ </div>
+ )
+}
diff --git a/products/streamlit_apps/frontend/StreamlitApps.tsx b/products/streamlit_apps/frontend/StreamlitApps.tsx
new file mode 100644
index 000000000000..168a11ba059e
--- /dev/null
+++ b/products/streamlit_apps/frontend/StreamlitApps.tsx
@@ -0,0 +1,137 @@
+import { useActions, useValues } from 'kea'
+import { router } from 'kea-router'
+
+import { IconEllipsis, IconPlus, IconTrash } from '@posthog/icons'
+import { LemonButton, LemonMenu, LemonTag, LemonTagType } from '@posthog/lemon-ui'
+
+import { NotFound } from 'lib/components/NotFound'
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
+import { Spinner } from 'lib/lemon-ui/Spinner/Spinner'
+import { SceneExport } from 'scenes/sceneTypes'
+import { urls } from 'scenes/urls'
+
+import type { AppSummaryContractApi } from './generated/api.schemas'
+import { streamlitAppsLogic } from './streamlitAppsLogic'
+import { StreamlitAppStatus, toStreamlitAppStatus } from './types'
+
+export const scene: SceneExport = {
+ component: StreamlitApps,
+ logic: streamlitAppsLogic,
+}
+
+const STATUS_CONFIG: Record<StreamlitAppStatus, { label: string; type: LemonTagType }> = {
+ running: { label: 'Running', type: 'success' },
+ starting: { label: 'Starting', type: 'warning' },
+ stopping: { label: 'Stopping', type: 'default' },
+ stopped: { label: 'Stopped', type: 'default' },
+ error: { label: 'Error', type: 'danger' },
+}
+
+function AppCard({ app }: { app: AppSummaryContractApi }): JSX.Element {
+ const config = STATUS_CONFIG[toStreamlitAppStatus(app.status)]
+ const { deleteStreamlitApp } = useActions(streamlitAppsLogic)
+
+ const openApp = (): void => {
+ router.actions.push(urls.streamlitApp(app.short_id))
+ }
+
+ return (
+ <div
+ className="border rounded-lg p-4 cursor-pointer hover:shadow-md transition-shadow bg-bg-light focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary"
+ onClick={openApp}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault()
+ openApp()
+ }
+ }}
+ role="link"
+ tabIndex={0}
+ aria-label={`Open ${app.name}`}
+ >
+ <div className="flex items-start justify-between mb-2">
+ <h3 className="font-semibold text-base m-0 truncate">{app.name}</h3>
+ <div className="flex items-center gap-1">
+ <LemonTag type={config.type}>{config.label}</LemonTag>
+ <LemonMenu
+ items={[
+ {
+ label: 'Delete',
+ icon: <IconTrash />,
+ status: 'danger',
+ onClick: () => {
+ LemonDialog.open({
+ title: 'Delete app?',
+ description:
+ 'This will permanently delete this app and all its versions. This cannot be undone.',
+ primaryButton: {
+ children: 'Delete',
+ status: 'danger',
+ onClick: () => deleteStreamlitApp({ shortId: app.short_id }),
+ },
+ secondaryButton: {
+ children: 'Cancel',
+ },
+ })
+ },
+ },
+ ]}
+ placement="bottom-end"
+ >
+ <LemonButton
+ size="xsmall"
+ noPadding
+ icon={<IconEllipsis />}
+ onClick={(e) => e.stopPropagation()}
+ />
+ </LemonMenu>
+ </div>
+ </div>
+ {app.description && <p className="text-muted text-sm mb-2 line-clamp-2 m-0">{app.description}</p>}
+ <div className="flex items-center justify-end text-xs text-muted mt-3">
+ <span>{app.created_by?.first_name ?? 'Unknown'}</span>
+ </div>
+ </div>
+ )
+}
+
+export function StreamlitApps(): JSX.Element {
+ const streamlitAppsFeatureFlagEnabled = useFeatureFlag('STREAMLIT_APPS')
+ const { streamlitApps, streamlitAppsLoading } = useValues(streamlitAppsLogic)
+
+ if (!streamlitAppsFeatureFlagEnabled) {
+ return <NotFound object="page" />
+ }
+
+ return (
+ <div>
+ <div className="flex items-center justify-between mb-4">
+ <h1 className="text-2xl font-bold m-0">Apps</h1>
+ <LemonButton type="primary" icon={<IconPlus />} to={urls.streamlitAppNew()}>
+ New app
+ </LemonButton>
+ </div>
+
+ {streamlitAppsLoading && streamlitApps.length === 0 ? (
+ <div className="flex items-center justify-center py-20">
+ <Spinner className="text-4xl" />
+ </div>
+ ) : streamlitApps.length === 0 ? (
+ <div className="flex flex-col items-center justify-center py-20 text-center">
+ <h2 className="text-lg font-semibold mb-2">No apps yet</h2>
+ <p className="text-muted mb-4">Create your first Streamlit app to get started.</p>
+ <LemonButton type="primary" icon={<IconPlus />} to={urls.streamlitAppNew()}>
+ New app
+ </LemonButton>
+ </div>
+ ) : (
+ <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
+ {streamlitApps.map((app) => (
+ <AppCard key={app.id} app={app} />
+ ))}
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/products/streamlit_apps/frontend/generated/api.schemas.ts b/products/streamlit_apps/frontend/generated/api.schemas.ts
index f959e957867c..dda4b8a3c3e1 100644
--- a/products/streamlit_apps/frontend/generated/api.schemas.ts
+++ b/products/streamlit_apps/frontend/generated/api.schemas.ts
@@ -28,7 +28,7 @@ export interface StreamlitAppUserInfoApi {
role_at_organization: string | null
}
-export interface AppContractApi {
+export interface AppSummaryContractApi {
/** User who created this app. */
created_by?: StreamlitAppUserInfoApi | null
id: string
@@ -42,13 +42,13 @@ export interface AppContractApi {
updated_at: string
}
-export interface PaginatedAppContractListApi {
+export interface PaginatedAppSummaryContractListApi {
count: number
/** @nullable */
next?: string | null
/** @nullable */
previous?: string | null
- results: AppContractApi[]
+ results: AppSummaryContractApi[]
}
export interface CreateAppInputApi {
@@ -62,6 +62,47 @@ export interface CreateAppInputApi {
memory_gb?: 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 AppSandboxContractApi {
+ status: string
+ restart_count: number
+ last_error: string
+ /** @nullable */
+ started_at: string | null
+ /** @nullable */
+ last_activity_at: string | null
+ /** @nullable */
+ version_number: number | null
+}
+
+export interface AppContractApi {
+ /** User who created this app. */
+ created_by?: StreamlitAppUserInfoApi | null
+ /** Currently active version, or null if none uploaded yet. */
+ active_version?: AppVersionContractApi | null
+ /** Current sandbox state, or null if the app has never started. */
+ sandbox?: AppSandboxContractApi | 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 UpdateAppInputApi {
/** New name for the app. */
name?: string
@@ -89,17 +130,6 @@ export interface ActivateVersionRequestApi {
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
diff --git a/products/streamlit_apps/frontend/generated/api.ts b/products/streamlit_apps/frontend/generated/api.ts
index 5521e31cbbb9..4ac19bb2020f 100644
--- a/products/streamlit_apps/frontend/generated/api.ts
+++ b/products/streamlit_apps/frontend/generated/api.ts
@@ -14,7 +14,7 @@ import type {
AppContractApi,
AppVersionContractApi,
CreateAppInputApi,
- PaginatedAppContractListApi,
+ PaginatedAppSummaryContractListApi,
PatchedUpdateAppInputApi,
StreamlitAppStatusApi,
StreamlitAppVersionListApi,
@@ -47,8 +47,8 @@ export const streamlitAppsList = async (
projectId: string,
params?: StreamlitAppsListParams,
options?: RequestInit
-): Promise<PaginatedAppContractListApi> => {
- return apiMutator<PaginatedAppContractListApi>(getStreamlitAppsListUrl(projectId, params), {
+): Promise<PaginatedAppSummaryContractListApi> => {
+ return apiMutator<PaginatedAppSummaryContractListApi>(getStreamlitAppsListUrl(projectId, params), {
...options,
method: 'GET',
})
diff --git a/products/streamlit_apps/frontend/streamlitAppEditLogic.ts b/products/streamlit_apps/frontend/streamlitAppEditLogic.ts
new file mode 100644
index 000000000000..33f94deeb834
--- /dev/null
+++ b/products/streamlit_apps/frontend/streamlitAppEditLogic.ts
@@ -0,0 +1,349 @@
+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+import { router } from 'kea-router'
+
+import { lemonToast } from '@posthog/lemon-ui'
+
+import api from 'lib/api'
+import { projectLogic } from 'scenes/projectLogic'
+import { urls } from 'scenes/urls'
+
+import { Breadcrumb } from '~/types'
+
+import {
+ getStreamlitAppsUploadVersionCreateUrl,
+ streamlitAppsActivateVersionCreate,
+ streamlitAppsCreate,
+ streamlitAppsDestroy,
+ streamlitAppsRetrieve,
+ streamlitAppsUpdate,
+ streamlitAppsVersionsRetrieve,
+} from './generated/api'
+import type { AppContractApi, AppVersionContractApi } from './generated/api.schemas'
+import { streamlitAppsLogic } from './streamlitAppsLogic'
+
+export interface StreamlitAppEditLogicProps {
+ shortId: string
+}
+
+// The generated client JSON-encodes its body, so it can't carry the zip. Only the body is
+// hand-rolled — the URL still comes from the generated builder.
+async function uploadAppVersion(projectId: string, shortId: string, file: File): Promise<AppVersionContractApi> {
+ const formData = new FormData()
+ formData.append('file', file)
+ // nosemgrep: prefer-codegen-api
+ return await api.create<AppVersionContractApi>(getStreamlitAppsUploadVersionCreateUrl(projectId, shortId), formData)
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface streamlitAppEditLogicValues {
+ currentProjectId: number | null // projectLogic
+ breadcrumbs: Breadcrumb[]
+ cpuCores: number
+ description: string
+ memoryGb: number
+ name: string
+ savedApp: AppContractApi | null
+ savedAppLoading: boolean
+ streamlitApp: AppContractApi | null
+ streamlitAppLoading: boolean
+ versions: AppVersionContractApi[]
+ versionsLoading: boolean
+ zipFile: File | null
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface streamlitAppEditLogicActions {
+ deleteApp: () => any
+ deleteAppFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ deleteAppSuccess: (
+ savedApp: null,
+ payload?: any
+ ) => {
+ savedApp: null
+ payload?: any
+ }
+ loadStreamlitApp: () => any
+ loadStreamlitAppFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadStreamlitAppSuccess: (
+ streamlitApp: AppContractApi | null,
+ payload?: any
+ ) => {
+ streamlitApp: AppContractApi | null
+ payload?: any
+ }
+ loadVersions: () => any
+ loadVersionsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadVersionsSuccess: (
+ versions: AppVersionContractApi[],
+ payload?: any
+ ) => {
+ versions: AppVersionContractApi[]
+ payload?: any
+ }
+ saveApp: () => any
+ saveAppFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ saveAppSuccess: (
+ savedApp: AppContractApi,
+ payload?: any
+ ) => {
+ savedApp: AppContractApi
+ payload?: any
+ }
+ setActiveVersionInState: (activeVersion: AppVersionContractApi) => {
+ activeVersion: AppVersionContractApi
+ }
+ setActiveVersionNumber: (versionNumber: number) => {
+ versionNumber: number
+ }
+ setCpuCores: (cpuCores: number) => {
+ cpuCores: number
+ }
+ setDescription: (description: string) => {
+ description: string
+ }
+ setMemoryGb: (memoryGb: number) => {
+ memoryGb: number
+ }
+ setName: (name: string) => {
+ name: string
+ }
+ setZipFile: (file: File | null) => {
+ file: File | null
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface streamlitAppEditLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ breadcrumbs: (streamlitApp: AppContractApi | null) => Breadcrumb[]
+ }
+}
+
+export type streamlitAppEditLogicType = MakeLogicType<
+ streamlitAppEditLogicValues,
+ streamlitAppEditLogicActions,
+ StreamlitAppEditLogicProps,
+ streamlitAppEditLogicMeta
+>
+
+export const streamlitAppEditLogic = kea<streamlitAppEditLogicType>([
+ path(['products', 'streamlit_apps', 'frontend', 'streamlitAppEditLogic']),
+ props({} as StreamlitAppEditLogicProps),
+ key((props) => props.shortId),
+
+ connect(() => ({
+ values: [projectLogic, ['currentProjectId']],
+ })),
+
+ actions({
+ setName: (name: string) => ({ name }),
+ setDescription: (description: string) => ({ description }),
+ setCpuCores: (cpuCores: number) => ({ cpuCores }),
+ setMemoryGb: (memoryGb: number) => ({ memoryGb }),
+ setZipFile: (file: File | null) => ({ file }),
+ setActiveVersionNumber: (versionNumber: number) => ({ versionNumber }),
+ // Narrow update; dispatching loadStreamlitAppSuccess would clobber unsaved form edits.
+ setActiveVersionInState: (activeVersion: AppVersionContractApi) => ({ activeVersion }),
+ }),
+
+ loaders(({ props, values }) => ({
+ streamlitApp: [
+ null as AppContractApi | null,
+ {
+ loadStreamlitApp: async () => {
+ if (props.shortId === 'new') {
+ return null
+ }
+ return await streamlitAppsRetrieve(String(values.currentProjectId), props.shortId)
+ },
+ },
+ ],
+ versions: [
+ [] as AppVersionContractApi[],
+ {
+ loadVersions: async () => {
+ if (props.shortId === 'new') {
+ return []
+ }
+ const response = await streamlitAppsVersionsRetrieve(String(values.currentProjectId), props.shortId)
+ return response.results
+ },
+ },
+ ],
+ savedApp: [
+ null as AppContractApi | null,
+ {
+ saveApp: async () => {
+ const isNew = props.shortId === 'new'
+ const projectId = String(values.currentProjectId)
+
+ let app: AppContractApi
+ if (isNew) {
+ app = await streamlitAppsCreate(projectId, {
+ name: values.name,
+ description: values.description,
+ cpu_cores: values.cpuCores,
+ memory_gb: values.memoryGb,
+ })
+ } else {
+ app = await streamlitAppsUpdate(projectId, props.shortId, {
+ name: values.name,
+ description: values.description,
+ cpu_cores: values.cpuCores,
+ memory_gb: values.memoryGb,
+ })
+ }
+
+ if (values.zipFile) {
+ try {
+ await uploadAppVersion(projectId, app.short_id, values.zipFile)
+ app = await streamlitAppsRetrieve(projectId, app.short_id)
+ } catch {
+ lemonToast.error('App created but zip upload failed. You can retry from the edit page.')
+ router.actions.push(urls.streamlitAppEdit(app.short_id))
+ return app
+ }
+ }
+
+ lemonToast.success(isNew ? 'App created' : 'App saved')
+ if (isNew) {
+ router.actions.push(urls.streamlitApp(app.short_id))
+ }
+ return app
+ },
+ deleteApp: async () => {
+ await streamlitAppsDestroy(String(values.currentProjectId), props.shortId)
+ lemonToast.success('App deleted')
+ streamlitAppsLogic.findMounted()?.actions.loadStreamlitApps()
+ router.actions.push(urls.streamlitApps())
+ return null
+ },
+ },
+ ],
+ })),
+
+ reducers({
+ streamlitApp: {
+ setActiveVersionInState: (state: AppContractApi | null, { activeVersion }) =>
+ state ? { ...state, active_version: activeVersion } : state,
+ },
+ name: [
+ '',
+ {
+ setName: (_, { name }) => name,
+ loadStreamlitAppSuccess: (_, { streamlitApp }) => streamlitApp?.name ?? '',
+ },
+ ],
+ description: [
+ '',
+ {
+ setDescription: (_, { description }) => description,
+ loadStreamlitAppSuccess: (_, { streamlitApp }) => streamlitApp?.description ?? '',
+ },
+ ],
+ cpuCores: [
+ 0.5,
+ {
+ setCpuCores: (_, { cpuCores }) => cpuCores,
+ loadStreamlitAppSuccess: (_, { streamlitApp }) => streamlitApp?.cpu_cores ?? 0.5,
+ },
+ ],
+ memoryGb: [
+ 1,
+ {
+ setMemoryGb: (_, { memoryGb }) => memoryGb,
+ loadStreamlitAppSuccess: (_, { streamlitApp }) => streamlitApp?.memory_gb ?? 1,
+ },
+ ],
+ zipFile: [
+ null as File | null,
+ {
+ setZipFile: (_, { file }) => file,
+ },
+ ],
+ }),
+
+ selectors({
+ breadcrumbs: [
+ (s) => [s.streamlitApp],
+ (streamlitApp: AppContractApi | null): Breadcrumb[] => [
+ {
+ key: 'StreamlitApps',
+ name: 'Apps',
+ path: urls.streamlitApps(),
+ },
+ {
+ key: ['StreamlitAppEdit', streamlitApp?.short_id || 'new'],
+ name: streamlitApp ? streamlitApp.name : 'New app',
+ },
+ ],
+ ],
+ }),
+
+ listeners(({ props, values, actions }) => ({
+ saveAppSuccess: ({ savedApp }) => {
+ if (savedApp) {
+ streamlitAppsLogic.findMounted()?.actions.updateStreamlitApp(savedApp)
+ }
+ },
+ setActiveVersionNumber: async ({ versionNumber }) => {
+ if (props.shortId === 'new') {
+ return
+ }
+ try {
+ const response = await streamlitAppsActivateVersionCreate(
+ String(values.currentProjectId),
+ props.shortId,
+ { version_number: versionNumber }
+ )
+ lemonToast.success(`Switched to v${versionNumber}. Restart the app to apply.`)
+ const nextActiveVersion = response?.active_version ?? values.streamlitApp?.active_version ?? null
+ if (values.streamlitApp && nextActiveVersion) {
+ // Narrow update; see setActiveVersionInState for rationale.
+ actions.setActiveVersionInState(nextActiveVersion)
+ streamlitAppsLogic.findMounted()?.actions.updateStreamlitApp({
+ ...values.streamlitApp,
+ active_version: nextActiveVersion,
+ })
+ }
+ } catch (error: any) {
+ lemonToast.error(
+ `Failed to activate v${versionNumber}: ${error?.detail || error?.message || 'unknown error'}`
+ )
+ }
+ },
+ })),
+
+ afterMount(({ props, actions }) => {
+ if (props.shortId !== 'new') {
+ actions.loadStreamlitApp()
+ actions.loadVersions()
+ }
+ }),
+])
diff --git a/products/streamlit_apps/frontend/streamlitAppLogic.ts b/products/streamlit_apps/frontend/streamlitAppLogic.ts
new file mode 100644
index 000000000000..9331f68753d0
--- /dev/null
+++ b/products/streamlit_apps/frontend/streamlitAppLogic.ts
@@ -0,0 +1,428 @@
+import {
+ MakeLogicType,
+ actions,
+ afterMount,
+ beforeUnmount,
+ connect,
+ kea,
+ key,
+ listeners,
+ path,
+ props,
+ reducers,
+ selectors,
+} from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { projectLogic } from 'scenes/projectLogic'
+import { urls } from 'scenes/urls'
+
+import { Breadcrumb } from '~/types'
+
+import {
+ streamlitAppsConnectInfoRetrieve,
+ streamlitAppsRestartCreate,
+ streamlitAppsRetrieve,
+ streamlitAppsStartCreate,
+ streamlitAppsStatusRetrieve,
+ streamlitAppsStopCreate,
+} from './generated/api'
+import type { AppContractApi, AppSandboxContractApi, StreamlitConnectInfoApi } from './generated/api.schemas'
+import { StreamlitAppStatus, toStreamlitAppStatus } from './types'
+
+export interface StreamlitAppLogicProps {
+ shortId: string
+}
+
+const POLL_INTERVAL_MS = 2000
+const HEALTH_POLL_INTERVAL_MS = 15000
+const TOKEN_REFRESH_RATIO = 0.8
+// Floor prevents a malformed expires_in from scheduling an immediate refresh loop.
+const MIN_TOKEN_REFRESH_MS = 5_000
+
+type TimerKey = 'pollTimer' | 'healthPollTimer' | 'tokenRefreshTimer'
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface streamlitAppLogicValues {
+ currentProjectId: number | null // projectLogic
+ appStatus: StreamlitAppStatus
+ breadcrumbs: Breadcrumb[]
+ connectError: string | null
+ connectInfo: StreamlitConnectInfoApi | null
+ connectInfoLoading: boolean
+ iframeSrc: string | null
+ isHealthPolling: boolean
+ isPolling: boolean
+ sandboxStatus: AppSandboxContractApi | null
+ sandboxStatusLoading: boolean
+ streamlitApp: AppContractApi | null
+ streamlitAppLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface streamlitAppLogicActions {
+ clearTokenRefresh: () => {
+ value: true
+ }
+ loadConnectInfo: () => any
+ loadConnectInfoFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadConnectInfoSuccess: (
+ connectInfo: StreamlitConnectInfoApi,
+ payload?: any
+ ) => {
+ connectInfo: StreamlitConnectInfoApi
+ payload?: any
+ }
+ loadSandboxStatus: () => any
+ loadSandboxStatusFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadSandboxStatusSuccess: (
+ sandboxStatus: {
+ last_activity_at: string | null
+ last_error: string
+ restart_count: number
+ started_at: string | null
+ status: string
+ version_number: number | null
+ },
+ payload?: any
+ ) => {
+ sandboxStatus: {
+ last_activity_at: string | null
+ last_error: string
+ restart_count: number
+ started_at: string | null
+ status: string
+ version_number: number | null
+ }
+ payload?: any
+ }
+ loadStreamlitApp: () => any
+ loadStreamlitAppFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadStreamlitAppSuccess: (
+ streamlitApp: AppContractApi,
+ payload?: any
+ ) => {
+ streamlitApp: AppContractApi
+ payload?: any
+ }
+ restartApp: () => any
+ restartAppFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ restartAppSuccess: (
+ sandboxStatus: AppSandboxContractApi | null,
+ payload?: any
+ ) => {
+ sandboxStatus: AppSandboxContractApi | null
+ payload?: any
+ }
+ scheduleTokenRefresh: (expiresIn: number) => {
+ expiresIn: number
+ }
+ startApp: () => any
+ startAppFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ startAppSuccess: (
+ sandboxStatus: AppSandboxContractApi | null,
+ payload?: any
+ ) => {
+ sandboxStatus: AppSandboxContractApi | null
+ payload?: any
+ }
+ startHealthPolling: () => {
+ value: true
+ }
+ startPolling: () => {
+ value: true
+ }
+ stopApp: () => any
+ stopAppFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ stopAppSuccess: (
+ sandboxStatus: AppSandboxContractApi | null,
+ payload?: any
+ ) => {
+ sandboxStatus: AppSandboxContractApi | null
+ payload?: any
+ }
+ stopHealthPolling: () => {
+ value: true
+ }
+ stopPolling: () => {
+ value: true
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface streamlitAppLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ breadcrumbs: (streamlitApp: AppContractApi | null) => Breadcrumb[]
+ appStatus: (sandboxStatus: AppSandboxContractApi | null) => StreamlitAppStatus
+ iframeSrc: (
+ appStatus: 'error' | 'running' | 'starting' | 'stopped' | 'stopping',
+ connectInfo: StreamlitConnectInfoApi | null
+ ) => string | null
+ }
+}
+
+export type streamlitAppLogicType = MakeLogicType<
+ streamlitAppLogicValues,
+ streamlitAppLogicActions,
+ StreamlitAppLogicProps,
+ streamlitAppLogicMeta
+>
+
+export const streamlitAppLogic = kea<streamlitAppLogicType>([
+ path(['products', 'streamlit_apps', 'frontend', 'streamlitAppLogic']),
+ props({} as StreamlitAppLogicProps),
+ key((props) => props.shortId),
+
+ connect(() => ({
+ values: [projectLogic, ['currentProjectId']],
+ })),
+
+ actions({
+ startPolling: true,
+ stopPolling: true,
+ startHealthPolling: true,
+ stopHealthPolling: true,
+ scheduleTokenRefresh: (expiresIn: number) => ({ expiresIn }),
+ clearTokenRefresh: true,
+ }),
+
+ loaders(({ props, values }) => ({
+ streamlitApp: [
+ null as AppContractApi | null,
+ {
+ loadStreamlitApp: async () => {
+ return await streamlitAppsRetrieve(String(values.currentProjectId), props.shortId)
+ },
+ },
+ ],
+ sandboxStatus: [
+ null as AppSandboxContractApi | null,
+ {
+ loadSandboxStatus: async () => {
+ const status = await streamlitAppsStatusRetrieve(String(values.currentProjectId), props.shortId)
+ // The status action omits version_number when stopped; the embedded sandbox
+ // always carries it, so normalize to one shape.
+ return { ...status, version_number: status.version_number ?? null }
+ },
+ startApp: async () => {
+ const app = await streamlitAppsStartCreate(String(values.currentProjectId), props.shortId)
+ return app.sandbox ?? null
+ },
+ stopApp: async () => {
+ const app = await streamlitAppsStopCreate(String(values.currentProjectId), props.shortId)
+ return app.sandbox ?? null
+ },
+ restartApp: async () => {
+ const app = await streamlitAppsRestartCreate(String(values.currentProjectId), props.shortId)
+ return app.sandbox ?? null
+ },
+ },
+ ],
+ connectInfo: [
+ null as StreamlitConnectInfoApi | null,
+ {
+ loadConnectInfo: async () => {
+ return await streamlitAppsConnectInfoRetrieve(String(values.currentProjectId), props.shortId)
+ },
+ },
+ ],
+ })),
+
+ reducers({
+ isPolling: [
+ false,
+ {
+ startPolling: () => true,
+ stopPolling: () => false,
+ },
+ ],
+ isHealthPolling: [
+ false,
+ {
+ startHealthPolling: () => true,
+ stopHealthPolling: () => false,
+ },
+ ],
+ connectError: [
+ null as string | null,
+ {
+ loadConnectInfoFailure: (_, { error }) => String(error),
+ loadConnectInfoSuccess: () => null,
+ startApp: () => null,
+ restartApp: () => null,
+ },
+ ],
+ connectInfo: {
+ // Restart mints a new sandbox — clear so we refetch fresh tokens.
+ restartApp: () => null,
+ restartAppSuccess: () => null,
+ },
+ }),
+
+ selectors({
+ breadcrumbs: [
+ (s) => [s.streamlitApp],
+ (streamlitApp: AppContractApi | null): Breadcrumb[] => [
+ {
+ key: 'StreamlitApps',
+ name: 'Apps',
+ path: urls.streamlitApps(),
+ },
+ {
+ key: ['StreamlitApp', streamlitApp?.short_id || 'new'],
+ name: streamlitApp?.name || 'Loading...',
+ },
+ ],
+ ],
+ appStatus: [
+ (s) => [s.sandboxStatus],
+ (sandboxStatus: AppSandboxContractApi | null): StreamlitAppStatus =>
+ toStreamlitAppStatus(sandboxStatus?.status),
+ ],
+ iframeSrc: [
+ (s) => [s.appStatus, s.connectInfo],
+ (appStatus: StreamlitAppStatus, connectInfo: StreamlitConnectInfoApi | null): string | null => {
+ if (appStatus !== 'running' || !connectInfo) {
+ return null
+ }
+ return connectInfo.iframe_url
+ },
+ ],
+ }),
+
+ listeners(({ actions, values, cache }) => {
+ // Idempotent — kea listeners can fire repeatedly and timers would stack.
+ // clearInterval also accepts timeout IDs, so this covers both.
+ const clearCached = (key: TimerKey): void => {
+ if (cache[key]) {
+ clearInterval(cache[key])
+ cache[key] = null
+ }
+ }
+ return {
+ loadStreamlitAppSuccess: ({ streamlitApp }) => {
+ if (!streamlitApp) {
+ return
+ }
+ // Seed sandboxStatus from app data so appStatus is correct immediately.
+ if (streamlitApp.sandbox) {
+ actions.loadSandboxStatusSuccess(streamlitApp.sandbox)
+ }
+ const status = streamlitApp.sandbox?.status ?? 'stopped'
+ if (status === 'starting') {
+ actions.startPolling()
+ } else if (status === 'running') {
+ actions.loadConnectInfo()
+ }
+ },
+ startAppSuccess: () => {
+ actions.startPolling()
+ },
+ startPolling: () => {
+ clearCached('pollTimer')
+ cache.pollTimer = setInterval(() => {
+ actions.loadSandboxStatus()
+ }, POLL_INTERVAL_MS)
+ },
+ stopPolling: () => clearCached('pollTimer'),
+ startHealthPolling: () => {
+ clearCached('healthPollTimer')
+ cache.healthPollTimer = setInterval(() => {
+ actions.loadSandboxStatus()
+ }, HEALTH_POLL_INTERVAL_MS)
+ },
+ stopHealthPolling: () => clearCached('healthPollTimer'),
+ loadSandboxStatusSuccess: ({ sandboxStatus }) => {
+ if (!sandboxStatus) {
+ return
+ }
+ if (sandboxStatus.status === 'running') {
+ actions.stopPolling()
+ if (!values.isHealthPolling) {
+ actions.startHealthPolling()
+ }
+ if (!values.connectInfo) {
+ actions.loadConnectInfo()
+ }
+ } else if (sandboxStatus.status === 'error' || sandboxStatus.status === 'stopped') {
+ actions.stopPolling()
+ actions.stopHealthPolling()
+ actions.clearTokenRefresh()
+ }
+ },
+ loadConnectInfoSuccess: ({ connectInfo }) => {
+ if (connectInfo) {
+ actions.scheduleTokenRefresh(connectInfo.expires_in)
+ }
+ },
+ scheduleTokenRefresh: ({ expiresIn }) => {
+ actions.clearTokenRefresh()
+ const refreshMs = Math.max(expiresIn * TOKEN_REFRESH_RATIO * 1000, MIN_TOKEN_REFRESH_MS)
+ cache.tokenRefreshTimer = setTimeout(() => {
+ actions.loadConnectInfo()
+ }, refreshMs)
+ },
+ loadConnectInfoFailure: () => {
+ // Don't reschedule — a 5s retry loop would hammer a broken sandbox.
+ actions.clearTokenRefresh()
+ },
+ clearTokenRefresh: () => clearCached('tokenRefreshTimer'),
+ stopAppSuccess: () => {
+ actions.stopPolling()
+ actions.stopHealthPolling()
+ actions.clearTokenRefresh()
+ },
+ restartAppSuccess: () => {
+ actions.startPolling()
+ actions.clearTokenRefresh()
+ },
+ }
+ }),
+
+ afterMount(({ actions }) => {
+ actions.loadStreamlitApp()
+ }),
+
+ beforeUnmount(({ actions }) => {
+ actions.stopPolling()
+ actions.stopHealthPolling()
+ actions.clearTokenRefresh()
+ }),
+])
diff --git a/products/streamlit_apps/frontend/streamlitAppsLogic.ts b/products/streamlit_apps/frontend/streamlitAppsLogic.ts
new file mode 100644
index 000000000000..d54179d88e81
--- /dev/null
+++ b/products/streamlit_apps/frontend/streamlitAppsLogic.ts
@@ -0,0 +1,182 @@
+import { MakeLogicType, actions, afterMount, beforeUnmount, connect, kea, listeners, path, reducers } from 'kea'
+import { loaders } from 'kea-loaders'
+import { router } from 'kea-router'
+
+import { lemonToast } from '@posthog/lemon-ui'
+
+import { projectLogic } from 'scenes/projectLogic'
+import { urls } from 'scenes/urls'
+
+import { streamlitAppsCreate, streamlitAppsDestroy, streamlitAppsList } from './generated/api'
+import type { AppContractApi, AppSummaryContractApi } from './generated/api.schemas'
+
+const LIST_POLL_INTERVAL_MS = 10_000
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface streamlitAppsLogicValues {
+ currentProjectId: number | null // projectLogic
+ streamlitApps: AppSummaryContractApi[]
+ streamlitAppsLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface streamlitAppsLogicActions {
+ createStreamlitApp: ({ name, description }: { description?: string; name: string }) => {
+ name: string
+ description?: string
+ }
+ createStreamlitAppFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ createStreamlitAppSuccess: (
+ streamlitApps: AppSummaryContractApi[],
+ payload?: {
+ name: string
+ description?: string
+ }
+ ) => {
+ streamlitApps: AppSummaryContractApi[]
+ payload?: {
+ name: string
+ description?: string
+ }
+ }
+ deleteStreamlitApp: ({ shortId }: { shortId: string }) => {
+ shortId: string
+ }
+ deleteStreamlitAppFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ deleteStreamlitAppSuccess: (
+ streamlitApps: AppSummaryContractApi[],
+ payload?: {
+ shortId: string
+ }
+ ) => {
+ streamlitApps: AppSummaryContractApi[]
+ payload?: {
+ shortId: string
+ }
+ }
+ loadStreamlitApps: () => any
+ loadStreamlitAppsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadStreamlitAppsSuccess: (
+ streamlitApps: AppSummaryContractApi[],
+ payload?: any
+ ) => {
+ streamlitApps: AppSummaryContractApi[]
+ payload?: any
+ }
+ startListPolling: () => {
+ value: true
+ }
+ stopListPolling: () => {
+ value: true
+ }
+ updateStreamlitApp: (app: AppContractApi | AppSummaryContractApi) => {
+ app: AppContractApi | AppSummaryContractApi
+ }
+}
+
+export type streamlitAppsLogicType = MakeLogicType<streamlitAppsLogicValues, streamlitAppsLogicActions>
+
+export const streamlitAppsLogic = kea<streamlitAppsLogicType>([
+ path(['products', 'streamlit_apps', 'frontend', 'streamlitAppsLogic']),
+
+ connect(() => ({
+ values: [projectLogic, ['currentProjectId']],
+ })),
+
+ actions({
+ updateStreamlitApp: (app: AppContractApi | AppSummaryContractApi) => ({ app }),
+ startListPolling: true,
+ stopListPolling: true,
+ }),
+
+ loaders(({ values }) => ({
+ streamlitApps: [
+ [] as AppSummaryContractApi[],
+ {
+ loadStreamlitApps: async () => {
+ const response = await streamlitAppsList(String(values.currentProjectId))
+ return response.results
+ },
+ createStreamlitApp: async ({ name, description }: { name: string; description?: string }) => {
+ const newApp = await streamlitAppsCreate(String(values.currentProjectId), { name, description })
+ lemonToast.success('App created')
+ router.actions.push(urls.streamlitAppEdit(newApp.short_id))
+ return [...values.streamlitApps, newApp]
+ },
+ deleteStreamlitApp: async ({ shortId }: { shortId: string }) => {
+ await streamlitAppsDestroy(String(values.currentProjectId), shortId)
+ lemonToast.success('App deleted')
+ return values.streamlitApps.filter((a) => a.short_id !== shortId)
+ },
+ },
+ ],
+ })),
+
+ reducers({
+ streamlitApps: {
+ updateStreamlitApp: (state, { app }) =>
+ state.map((a) => (a.short_id === app.short_id ? { ...a, ...app } : a)),
+ },
+ }),
+
+ listeners(({ actions, cache }) => ({
+ startListPolling: () => {
+ // Idempotent — timers stack otherwise on re-fire.
+ if (cache.listPollTimer) {
+ clearInterval(cache.listPollTimer)
+ }
+ cache.listPollTimer = setInterval(() => {
+ if (typeof document !== 'undefined' && document.visibilityState === 'hidden') {
+ return
+ }
+ actions.loadStreamlitApps()
+ }, LIST_POLL_INTERVAL_MS)
+ },
+ stopListPolling: () => {
+ if (cache.listPollTimer) {
+ clearInterval(cache.listPollTimer)
+ cache.listPollTimer = null
+ }
+ },
+ })),
+
+ afterMount(({ actions, cache }) => {
+ actions.loadStreamlitApps()
+ actions.startListPolling()
+ // Refetch on tab focus so returning users don't sit on stale state for a poll interval.
+ if (typeof document !== 'undefined') {
+ cache.visibilityHandler = (): void => {
+ if (document.visibilityState === 'visible') {
+ actions.loadStreamlitApps()
+ }
+ }
+ document.addEventListener('visibilitychange', cache.visibilityHandler)
+ }
+ }),
+
+ beforeUnmount(({ actions, cache }) => {
+ actions.stopListPolling()
+ if (typeof document !== 'undefined' && cache.visibilityHandler) {
+ document.removeEventListener('visibilitychange', cache.visibilityHandler)
+ cache.visibilityHandler = null
+ }
+ }),
+])
diff --git a/products/streamlit_apps/frontend/types.ts b/products/streamlit_apps/frontend/types.ts
new file mode 100644
index 000000000000..3c7f75e86a9c
--- /dev/null
+++ b/products/streamlit_apps/frontend/types.ts
@@ -0,0 +1,9 @@
+export const STREAMLIT_APP_STATUSES = ['starting', 'running', 'stopping', 'stopped', 'error'] as const
+
+export type StreamlitAppStatus = (typeof STREAMLIT_APP_STATUSES)[number]
+
+// The API types status as a free-form string. Unrecognized values fall back to stopped so
+// the UI never renders a running app it can't actually reach.
+export function toStreamlitAppStatus(status: string | undefined): StreamlitAppStatus {
+ return STREAMLIT_APP_STATUSES.includes(status as StreamlitAppStatus) ? (status as StreamlitAppStatus) : 'stopped'
+}
diff --git a/products/streamlit_apps/manifest.tsx b/products/streamlit_apps/manifest.tsx
index 2cf8b7689671..df5bd77ec718 100644
--- a/products/streamlit_apps/manifest.tsx
+++ b/products/streamlit_apps/manifest.tsx
@@ -1,7 +1,53 @@
-import { ProductManifest } from '~/types'
+import { urls } from 'scenes/urls'
+
+import { ProductItemCategory, ProductKey } from '~/queries/schema/schema-general'
+
+import { FEATURE_FLAGS } from '../../frontend/src/lib/constants'
+import { FileSystemIconColor, ProductManifest } from '../../frontend/src/types'
export const manifest: ProductManifest = {
name: 'Streamlit apps',
- treeItemsNew: [],
- treeItemsProducts: [],
+ urls: {
+ streamlitApps: (): string => '/streamlit-apps',
+ streamlitApp: (id: string): string => `/streamlit-apps/${id}`,
+ streamlitAppEdit: (id: string): string => `/streamlit-apps/${id}/edit`,
+ streamlitAppNew: (): string => '/streamlit-apps/new',
+ },
+ scenes: {
+ StreamlitApps: {
+ name: 'Streamlit apps',
+ import: () => import('./frontend/StreamlitApps'),
+ projectBased: true,
+ },
+ StreamlitApp: {
+ name: 'Streamlit app',
+ import: () => import('./frontend/StreamlitApp'),
+ projectBased: true,
+ },
+ StreamlitAppEdit: {
+ name: 'Edit Streamlit app',
+ import: () => import('./frontend/StreamlitAppEdit'),
+ projectBased: true,
+ },
+ },
+ routes: {
+ '/streamlit-apps': ['StreamlitApps', 'streamlitApps'],
+ '/streamlit-apps/new': ['StreamlitAppEdit', 'streamlitAppNew'],
+ '/streamlit-apps/:id': ['StreamlitApp', 'streamlitApp'],
+ '/streamlit-apps/:id/edit': ['StreamlitAppEdit', 'streamlitAppEdit'],
+ },
+ treeItemsProducts: [
+ {
+ path: 'Apps',
+ intents: [ProductKey.STREAMLIT_APPS],
+ href: urls.streamlitApps(),
+ type: 'streamlit_app',
+ category: ProductItemCategory.UNRELEASED,
+ flag: FEATURE_FLAGS.STREAMLIT_APPS,
+ iconType: 'tools',
+ iconColor: ['var(--color-product-data-pipeline-light)'] as FileSystemIconColor,
+ sceneKey: 'StreamlitApps',
+ sceneKeys: ['StreamlitApps', 'StreamlitApp', 'StreamlitAppEdit'],
+ },
+ ],
}
diff --git a/products/streamlit_apps/package.json b/products/streamlit_apps/package.json
index 5f60d81ca4b8..886add34f7df 100644
--- a/products/streamlit_apps/package.json
+++ b/products/streamlit_apps/package.json
@@ -3,5 +3,16 @@
"scripts": {
"backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests -v --tb=short",
"backend:contract-check": "echo 'Contract files unchanged'"
+ },
+ "dependencies": {
+ "kea": "catalog:",
+ "kea-loaders": "catalog:",
+ "kea-router": "catalog:"
+ },
+ "peerDependencies": {
+ "@posthog/icons": "*",
+ "@posthog/lemon-ui": "*",
+ "@types/react": "*",
+ "react": "*"
}
}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 3994dd1e4190..d90cdedd3439 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -9824,9 +9824,25 @@ export namespace Schemas {
customer_name: string | null;
}
+ export interface AppSandboxContract {
+ status: string;
+ restart_count: number;
+ last_error: string;
+ /** @nullable */
+ started_at: string | null;
+ /** @nullable */
+ last_activity_at: string | null;
+ /** @nullable */
+ version_number: number | null;
+ }
+
export interface AppContract {
/** User who created this app. */
created_by?: StreamlitAppUserInfo | null;
+ /** Currently active version, or null if none uploaded yet. */
+ active_version?: AppVersionContract | null;
+ /** Current sandbox state, or null if the app has never started. */
+ sandbox?: AppSandboxContract | null;
id: string;
short_id: string;
name: string;
@@ -9854,6 +9870,20 @@ export namespace Schemas {
totals: AppMetricsTotalsResponseTotals;
}
+ export interface AppSummaryContract {
+ /** 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 AppfiguresReviewSignalExtra {
stars: string | null;
version: string | null;
@@ -40846,13 +40876,13 @@ export namespace Schemas {
results: Announcement[];
}
- export interface PaginatedAppContractList {
+ export interface PaginatedAppSummaryContractList {
count: number;
/** @nullable */
next?: string | null;
/** @nullable */
previous?: string | null;
- results: AppContract[];
+ results: AppSummaryContract[];
}
export interface PaginatedApprovalPolicyList {